import { NextRequest, NextResponse } from "next/server";

const DWG2DXF_URL = process.env.DWG2DXF_URL ?? "http://localhost:5001";

export async function POST(req: NextRequest) {
  try {
    const formData = await req.formData();
    const file = formData.get("fileInput") as File | null;

    if (!file) {
      return NextResponse.json(
        { error: "Lipsește fișierul DWG." },
        { status: 400 },
      );
    }

    const name = file.name.replace(/[^a-zA-Z0-9._-]/g, "_");
    if (!name.toLowerCase().endsWith(".dwg")) {
      return NextResponse.json(
        { error: "Fișierul trebuie să fie .dwg" },
        { status: 400 },
      );
    }

    // Re-package for sidecar (field name: "file")
    const sidecarForm = new FormData();
    sidecarForm.append("file", file, name);

    const res = await fetch(`${DWG2DXF_URL}/convert`, {
      method: "POST",
      body: sidecarForm,
    });

    if (!res.ok) {
      const data = await res.json().catch(() => ({ error: res.statusText }));
      const errorMsg =
        typeof data === "object" && data !== null && "error" in data
          ? String((data as Record<string, unknown>).error)
          : `Eroare sidecar DWG: ${res.status}`;
      return NextResponse.json({ error: errorMsg }, { status: res.status });
    }

    const blob = await res.blob();
    const buffer = Buffer.from(await blob.arrayBuffer());
    const dxfName = name.replace(/\.dwg$/i, ".dxf");

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        "Content-Type": "application/dxf",
        "Content-Disposition": `attachment; filename="${dxfName}"`,
      },
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";

    if (
      message.includes("ECONNREFUSED") ||
      message.includes("fetch failed") ||
      message.includes("ENOTFOUND")
    ) {
      return NextResponse.json(
        {
          error:
            "Serviciul de conversie DWG nu este disponibil. Verificați că containerul dwg2dxf este pornit.",
        },
        { status: 503 },
      );
    }

    return NextResponse.json(
      { error: `Eroare la conversie DWG→DXF: ${message}` },
      { status: 500 },
    );
  }
}
