/**
 * GET /api/geoportal/cf-status?nrCad=...
 *
 * Checks if a CF extract exists for a given cadastral number.
 * Returns download info if available.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/core/storage/prisma";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const url = new URL(req.url);
  const nrCad = url.searchParams.get("nrCad")?.trim();

  if (!nrCad) {
    return NextResponse.json({ error: "nrCad obligatoriu" }, { status: 400 });
  }

  try {
    // Find the latest completed CF extract for this cadastral number
    const extract = await prisma.cfExtract.findFirst({
      where: {
        nrCadastral: nrCad,
        status: "completed",
        minioPath: { not: "" },
      },
      orderBy: { completedAt: "desc" },
      select: {
        id: true,
        nrCadastral: true,
        nrCF: true,
        status: true,
        minioPath: true,
        documentName: true,
        completedAt: true,
        expiresAt: true,
      },
    });

    if (!extract || !extract.minioPath) {
      return NextResponse.json({ available: false });
    }

    const expired = extract.expiresAt && new Date(extract.expiresAt) < new Date();

    return NextResponse.json({
      available: !expired,
      expired: !!expired,
      id: extract.id,
      nrCF: extract.nrCF,
      documentName: extract.documentName,
      completedAt: extract.completedAt?.toISOString(),
      downloadUrl: `/api/ancpi/download?id=${extract.id}`,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
