import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { DeliverableCreateInputSchema } from "@/lib/contracts/types";

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

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

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

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

  const { id: contractId } = await context.params;

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

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

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

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

    const input = parsed.data;

    const deliverable = await prisma.contractDeliverable.create({
      data: {
        contractId,
        title: input.title,
        dueDate: input.dueDate ? new Date(input.dueDate) : null,
        amountLinked: input.amountLinked ?? null,
        notes: input.notes ?? "",
        status: "PENDING",
      },
    });

    return NextResponse.json({
      ok: true,
      deliverable: {
        id: deliverable.id,
        contractId: deliverable.contractId,
        title: deliverable.title,
        dueDate: deliverable.dueDate ? deliverable.dueDate.toISOString() : null,
        amountLinked: deliverable.amountLinked ? Number(deliverable.amountLinked) : null,
        status: deliverable.status,
        deliveredAt: deliverable.deliveredAt ? deliverable.deliveredAt.toISOString() : null,
        approvedAt: deliverable.approvedAt ? deliverable.approvedAt.toISOString() : null,
        notes: deliverable.notes,
      },
    });
  } catch {
    return NextResponse.json({ error: "No fue posible crear el entregable." }, { status: 400 });
  }
}
