import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { createCaptureEvidenceLink } from "@/lib/capture";

type CreateCaptureLinkBody = {
  weekStart?: string;
  department?: string;
  rowId?: string;
  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 });
  }

  let body: CreateCaptureLinkBody;
  try {
    body = (await request.json()) as CreateCaptureLinkBody;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
  }

  try {
    const evidence = await createCaptureEvidenceLink({
      viewer: {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      weekStartInput: body.weekStart,
      department: body.department,
      rowId: body.rowId,
      initiativeId: body.initiativeId,
      taskId: body.taskId,
      title: body.title?.trim() ?? "",
      note: body.note,
      url: body.url?.trim() ?? "",
    });

    return NextResponse.json({ ok: true, evidence });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unable to create capture evidence link.";
    if (message === "Forbidden") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    if (message.includes("not found")) {
      return NextResponse.json({ error: message }, { status: 404 });
    }

    return NextResponse.json({ error: message }, { status: 400 });
  }
}
