import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { buildPdfFilename, generateProposalPdf, type ProposalPdfKind } from "@/lib/proposals/pdf";
import { ProposalWorkflowStateSchema } from "@/lib/proposals/workflow-state";

export const runtime = "nodejs";

function isSchemaNotReadyError(error: unknown) {
  return error instanceof Prisma.PrismaClientKnownRequestError && (error.code === "P2021" || error.code === "P2022");
}

function parseKind(value: string): ProposalPdfKind | null {
  if (value === "technical" || value === "economic" || value === "summary") {
    return value;
  }

  return null;
}

export async function GET(_: Request, context: { params: Promise<{ id: string; kind: string }> }) {
  const user = await requireAdminApiUser();

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

  try {
    const { id, kind: kindParam } = await context.params;
    const kind = parseKind(kindParam);
    if (!kind) {
      return NextResponse.json({ error: "Tipo de PDF invalido." }, { status: 400 });
    }

    const proposal = await prisma.proposal.findFirst({
      where: {
        id,
        userId: user.id,
      },
      select: {
        id: true,
        title: true,
        issuingEntity: true,
        summary: true,
        status: true,
        currentStep: true,
        completionPercent: true,
        updatedAt: true,
        workflowDraft: true,
      },
    });

    if (!proposal) {
      return NextResponse.json({ error: "Propuesta no encontrada." }, { status: 404 });
    }

    const workflowParsed = ProposalWorkflowStateSchema.safeParse(proposal.workflowDraft);
    if (!workflowParsed.success) {
      return NextResponse.json({ error: "No hay flujo persistido valido para generar PDF." }, { status: 400 });
    }

    const buffer = await generateProposalPdf({
      kind,
      proposal: {
        title: proposal.title,
        issuingEntity: proposal.issuingEntity,
        summary: proposal.summary,
        status: proposal.status,
        currentStep: proposal.currentStep,
        completionPercent: proposal.completionPercent,
        updatedAtIso: proposal.updatedAt.toISOString(),
      },
      workflow: workflowParsed.data,
    });

    const filename = buildPdfFilename({
      kind,
      title: proposal.title,
    });
    const body = new Uint8Array(buffer);

    return new NextResponse(body, {
      status: 200,
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${filename}"`,
        "Cache-Control": "no-store",
      },
    });
  } catch (error) {
    if (isSchemaNotReadyError(error)) {
      return NextResponse.json(
        { error: "La base de datos aun no tiene los campos de persistencia de Gestion de Licitaciones. Ejecuta prisma migrate para continuar." },
        { status: 503 },
      );
    }

    return NextResponse.json(
      {
        error: "No fue posible generar el PDF. Verifica que Playwright y Chromium esten disponibles en el entorno.",
      },
      { status: 400 },
    );
  }
}
