import { unlink } from "fs/promises";
import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { resolveStoragePath } from "@/lib/projects/capture";
import { canAccessProjects, canManageProjects } from "@/lib/projects/persistence";

export async function DELETE(_request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessProjects(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const record = await prisma.projectCaptureEvidence.findFirst({
    where: {
      id: context.params.id,
      department: DepartmentKey.proyectos,
    },
    select: {
      id: true,
      uploadedById: true,
      storagePath: true,
    },
  });

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

  const canManage = canManageProjects(session.user.role, session.user.department);
  const isUploader = record.uploadedById === session.user.id;

  if (!canManage && !isUploader) {
    return NextResponse.json({ error: "You can only delete your own evidence." }, { status: 403 });
  }

  await prisma.projectCaptureEvidence.delete({
    where: { id: record.id },
  });

  if (record.storagePath) {
    const absolute = resolveStoragePath(record.storagePath);
    if (absolute) {
      await unlink(absolute).catch(() => {
        // Best-effort cleanup.
      });
    }
  }

  return NextResponse.json({ ok: true });
}
