import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();

  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;

  try {
    // Fetch the entry to check ownership
    const entry = await db.costEntry.findUnique({
      where: { id },
    });

    if (!entry) {
      return NextResponse.json(
        { error: "Cost entry not found" },
        { status: 404 }
      );
    }

    if (entry.userId !== session.user.id) {
      return NextResponse.json(
        { error: "You can only delete your own cost entries" },
        { status: 403 }
      );
    }

    await db.costEntry.delete({
      where: { id },
    });

    return NextResponse.json({ message: "Cost entry deleted" });
  } catch {
    return NextResponse.json(
      { error: "Failed to delete cost entry" },
      { status: 500 }
    );
  }
}
