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

type RouteContext = {
  params: Promise<{ id: string }>;
};

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

export async function PATCH(request: Request, context: RouteContext) {
  const user = await requireAdminApiUser();

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

  const { id } = await context.params;

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

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

    const owned = await prisma.legalCase.findFirst({
      where: {
        id,
        userId: user.id,
      },
      select: { id: true },
    });

    if (!owned) {
      return NextResponse.json({ error: "Caso no encontrado." }, { status: 404 });
    }

    const input = parsed.data;
    await prisma.legalCase.update({
      where: { id },
      data: {
        severity: input.severity,
        status: input.status,
        resolvedAt: input.resolvedAt === undefined ? undefined : input.resolvedAt ? new Date(input.resolvedAt) : null,
        description: input.description,
        amountAtRisk: input.amountAtRisk === undefined ? undefined : input.amountAtRisk ?? null,
        counterparty: input.counterparty,
      },
    });

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

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