import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { PaymentCreateInputSchema } 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 GET(_request: Request, context: RouteContext) {
  const user = await requireAdminApiUser();

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

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

  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 payments = await prisma.contractPayment.findMany({
    where: {
      contractId,
    },
    orderBy: [{ paymentDate: "desc" }, { createdAt: "desc" }],
  });

  return NextResponse.json({
    ok: true,
    payments: payments.map((item) => ({
      id: item.id,
      contractId: item.contractId,
      amount: Number(item.amount),
      paymentDate: item.paymentDate.toISOString(),
      invoiceNumber: item.invoiceNumber,
      concept: item.concept,
      status: item.status,
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString(),
    })),
  });
}

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 = PaymentCreateInputSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json({ error: "Datos de pago 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 payment = await prisma.contractPayment.create({
      data: {
        contractId,
        amount: input.amount,
        paymentDate: new Date(input.paymentDate),
        invoiceNumber: input.invoiceNumber ?? null,
        concept: input.concept,
        status: input.status ?? "REGISTERED",
      },
    });

    return NextResponse.json({
      ok: true,
      payment: {
        id: payment.id,
        contractId: payment.contractId,
        amount: Number(payment.amount),
        paymentDate: payment.paymentDate.toISOString(),
        invoiceNumber: payment.invoiceNumber,
        concept: payment.concept,
        status: payment.status,
        createdAt: payment.createdAt.toISOString(),
        updatedAt: payment.updatedAt.toISOString(),
      },
    });
  } catch {
    return NextResponse.json({ error: "No fue posible registrar el pago." }, { status: 400 });
  }
}
