import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { LegalCaseCreateInputSchema } from "@/lib/legal/types";
import { listLegalCasesForUser } from "@/lib/legal/server";

function parseJsonBody(body: unknown) {
  return typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
}

export async function GET() {
  const user = await requireAdminApiUser();

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

  const cases = await listLegalCasesForUser(user.id);
  return NextResponse.json({ ok: true, cases });
}

export async function POST(request: Request) {
  const user = await requireAdminApiUser();

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

  try {
    const body = parseJsonBody(await request.json().catch(() => ({})));
    const parsed = LegalCaseCreateInputSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json({ error: "Datos de caso legal invalidos." }, { status: 400 });
    }

    const input = parsed.data;

    const created = await prisma.legalCase.create({
      data: {
        userId: user.id,
        contractId: input.contractId ?? null,
        caseType: input.caseType,
        severity: input.severity,
        counterparty: input.counterparty,
        description: input.description,
        amountAtRisk: input.amountAtRisk ?? null,
        status: input.status ?? "OPEN",
      },
      select: {
        id: true,
      },
    });

    const cases = await listLegalCasesForUser(user.id);
    const legalCase = cases.find((item) => item.id === created.id) ?? null;

    return NextResponse.json({ ok: true, case: legalCase });
  } catch {
    return NextResponse.json({ error: "No fue posible crear el caso legal." }, { status: 400 });
  }
}
