import { NextResponse } from "next/server";
import { prisma } from "@/core/storage/prisma";
import { getCfExtractStream } from "@/modules/parcel-sync/services/epay-storage";
import JSZip from "jszip";

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

/**
 * GET /api/ancpi/download-zip?ids=id1,id2,id3
 *
 * Streams a ZIP file containing all requested CF extract PDFs.
 * Files named: {index:02d}_Extras CF_{nrCadastral} - {DD-MM-YYYY}.pdf
 * Index = position in the ids array (preserves list order).
 */
export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const idsParam = url.searchParams.get("ids");

    if (!idsParam) {
      return NextResponse.json(
        { error: "Parametru 'ids' lipsa." },
        { status: 400 },
      );
    }

    const ids = idsParam.split(",").map((s) => s.trim()).filter(Boolean);
    if (ids.length === 0) {
      return NextResponse.json(
        { error: "Lista de id-uri goala." },
        { status: 400 },
      );
    }

    // Fetch all extract records
    const extracts = await prisma.cfExtract.findMany({
      where: { id: { in: ids } },
      select: {
        id: true,
        nrCadastral: true,
        minioPath: true,
        documentDate: true,
        completedAt: true,
      },
    });

    // Build a map for ordering
    const extractMap = new Map(extracts.map((e) => [e.id, e]));

    const zip = new JSZip();
    let filesAdded = 0;

    for (let i = 0; i < ids.length; i++) {
      const id = ids[i]!;
      const extract = extractMap.get(id);
      if (!extract?.minioPath) continue;

      const dateForName = extract.documentDate ?? extract.completedAt ?? new Date();
      const d = new Date(dateForName);
      const dd = String(d.getDate()).padStart(2, "0");
      const mm = String(d.getMonth() + 1).padStart(2, "0");
      const yyyy = d.getFullYear();

      const idx = String(i + 1).padStart(2, "0");
      const fileName = `${idx}_Extras CF_${extract.nrCadastral} - ${dd}-${mm}-${yyyy}.pdf`;

      try {
        const stream = await getCfExtractStream(extract.minioPath);

        // Collect stream into buffer
        const chunks: Buffer[] = [];
        for await (const chunk of stream) {
          chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array));
        }
        const buffer = Buffer.concat(chunks);

        zip.file(fileName, buffer);
        filesAdded++;
      } catch (err) {
        console.error(`[download-zip] Failed to fetch ${extract.minioPath}:`, err);
        // Skip this file but continue
      }
    }

    if (filesAdded === 0) {
      return NextResponse.json(
        { error: "Niciun fisier PDF gasit." },
        { status: 404 },
      );
    }

    const zipBuffer = await zip.generateAsync({
      type: "nodebuffer",
      compression: "DEFLATE",
      compressionOptions: { level: 6 },
    });

    const today = new Date();
    const todayStr = `${String(today.getDate()).padStart(2, "0")}-${String(today.getMonth() + 1).padStart(2, "0")}-${today.getFullYear()}`;
    const archiveName = `Extrase_CF_${filesAdded}_${todayStr}.zip`;

    return new Response(new Uint8Array(zipBuffer), {
      headers: {
        "Content-Type": "application/zip",
        "Content-Disposition": `attachment; filename="${encodeURIComponent(archiveName)}"`,
        "Content-Length": String(zipBuffer.length),
      },
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
