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

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

/**
 * GET /api/ancpi/download?id={extractId}
 *
 * Streams the CF extract PDF from MinIO with proper filename.
 */
export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const id = url.searchParams.get("id");

    if (!id) {
      return NextResponse.json(
        { error: "Parametru 'id' lipsă." },
        { status: 400 },
      );
    }

    const extract = await prisma.cfExtract.findUnique({
      where: { id },
      select: { minioPath: true, nrCadastral: true, minioIndex: true },
    });

    if (!extract?.minioPath) {
      return NextResponse.json(
        { error: "Extras CF negăsit sau fără fișier." },
        { status: 404 },
      );
    }

    const stream = await getCfExtractStream(extract.minioPath);

    // Convert Node.js Readable to Web ReadableStream
    const webStream = new ReadableStream({
      start(controller) {
        stream.on("data", (chunk: Buffer) =>
          controller.enqueue(new Uint8Array(chunk)),
        );
        stream.on("end", () => controller.close());
        stream.on("error", (err: Error) => controller.error(err));
      },
    });

    // Build display filename
    const fileName =
      extract.minioPath.split("/").pop() ??
      `Extras_CF_${extract.nrCadastral}.pdf`;

    return new Response(webStream, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${encodeURIComponent(fileName)}"`,
      },
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
