import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { ContractUpdateInputSchema } from "@/lib/contracts/types";
import { listContractsForUser } from "@/lib/contracts/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 = ContractUpdateInputSchema.safeParse(body);

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

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

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

    const input = parsed.data;

    await prisma.contractRecord.update({
      where: { id },
      data: {
        title: input.title,
        counterpartyEntity: input.counterpartyEntity,
        contractNumber: input.contractNumber === undefined ? undefined : input.contractNumber ?? null,
        contractType: input.contractType,
        startDate: input.startDate === undefined ? undefined : input.startDate ? new Date(input.startDate) : null,
        endDate: input.endDate === undefined ? undefined : input.endDate ? new Date(input.endDate) : null,
        totalAmount: input.totalAmount === undefined ? undefined : input.totalAmount ?? null,
        currency: input.currency ? input.currency.toUpperCase() : undefined,
        status: input.status,
        description: input.description,
        sourceProposalId: input.sourceProposalId === undefined ? undefined : input.sourceProposalId ?? null,
      },
    });

    const contracts = await listContractsForUser(user.id, { q: id });
    const contract = contracts.find((item) => item.id === id) ?? null;

    return NextResponse.json({ ok: true, contract });
  } catch {
    return NextResponse.json({ error: "No fue posible actualizar el contrato." }, { status: 400 });
  }
}
