import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { toNormativeHistoryView } from "@/lib/normative-analysis/history";
import { prisma } from "@/lib/prisma";

function parsePositiveInt(value: string | null, fallback: number) {
  if (!value) {
    return fallback;
  }

  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return fallback;
  }

  return parsed;
}

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

export async function GET(request: Request) {
  const user = await requireAdminApiUser();

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

  try {
    const url = new URL(request.url);
    const take = Math.min(parsePositiveInt(url.searchParams.get("take"), 50), 100);
    const proposalId = url.searchParams.get("proposalId")?.trim() || null;
    let sourceLicitationId = url.searchParams.get("sourceId")?.trim() || null;

    if (!sourceLicitationId && proposalId) {
      const proposal = await prisma.proposal.findFirst({
        where: {
          id: proposalId,
          userId: user.id,
        },
        select: {
          sourceLicitationId: true,
        },
      });

      if (!proposal?.sourceLicitationId) {
        return NextResponse.json({
          ok: true,
          items: [],
        });
      }

      sourceLicitationId = proposal.sourceLicitationId;
    }

    const history = await prisma.normativeAnalysisHistory.findMany({
      where: {
        userId: user.id,
        deletedAt: null,
        ...(sourceLicitationId ? { sourceLicitationId } : {}),
      },
      orderBy: [{ analyzedAt: "desc" }],
      take,
      select: {
        id: true,
        sourceLicitationId: true,
        fileName: true,
        documentType: true,
        issuingEntity: true,
        methodUsed: true,
        numPages: true,
        warnings: true,
        extractedChars: true,
        analyzedAt: true,
        viabilityScore: true,
        riskLevel: true,
        confidence: true,
        result: true,
      },
    });

    return NextResponse.json({
      ok: true,
      items: history.map((entry) => toNormativeHistoryView(entry)),
    });
  } catch (error) {
    if (isSchemaNotReadyError(error)) {
      return NextResponse.json(
        { error: "La base de datos aun no tiene las tablas de Analisis Normativo. Ejecuta prisma migrate para continuar." },
        { status: 503 },
      );
    }

    return NextResponse.json({ error: "No fue posible consultar el historial." }, { status: 400 });
  }
}
