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 { validateCaptureAccess } from "@/lib/projects/capture-permissions";
import { canAccessProjects, mapProjectCaptureEvidence } from "@/lib/projects/persistence";

type CreateCaptureLinkBody = {
  initiativeId?: string;
  taskId?: string;
  title?: string;
  note?: string;
  url?: string;
};

export async function POST(request: Request) {
  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 body = (await request.json()) as CreateCaptureLinkBody;
  const title = body.title?.trim() ?? "";
  const note = body.note?.trim() || null;
  const rawUrl = body.url?.trim() ?? "";

  if (!title || !rawUrl) {
    return NextResponse.json({ error: "title and url are required." }, { status: 400 });
  }

  let normalizedUrl: string;
  try {
    normalizedUrl = new URL(rawUrl).toString();
  } catch {
    return NextResponse.json({ error: "Invalid url." }, { status: 400 });
  }

  const access = await validateCaptureAccess({
    userId: session.user.id,
    role: session.user.role,
    department: session.user.department,
    initiativeId: body.initiativeId,
    taskId: body.taskId,
  });

  if (!access.ok) {
    return NextResponse.json({ error: access.error }, { status: access.status });
  }

  const record = await prisma.projectCaptureEvidence.create({
    data: {
      department: DepartmentKey.proyectos,
      initiativeId: access.initiativeId,
      taskId: access.taskId,
      uploadedById: session.user.id,
      kind: "link",
      title,
      note,
      url: normalizedUrl,
    },
    include: {
      uploadedBy: {
        select: {
          name: true,
          email: true,
        },
      },
    },
  });

  return NextResponse.json({
    ok: true,
    evidence: mapProjectCaptureEvidence(record),
  });
}
