import { NextResponse } from "next/server";
import { env } from "@/lib/config";
import { getSession } from "@/lib/auth/session";

// Proxy /api/report_templates_apply.php — forwards the multipart payload to
// the backend with the Bearer JWT. The backend defaults to dry_run=1 when the
// flag is missing or non-"0" — cf handoff Q4 (2026-05-08).

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return NextResponse.json(
      { success: false, message: "Non authentifié" },
      { status: 401 },
    );
  }

  let form: FormData;
  try {
    form = await request.formData();
  } catch {
    return NextResponse.json(
      { success: false, message: "Requête multipart invalide" },
      { status: 400 },
    );
  }

  const target = `${env.apiBaseUrl}/report_templates_apply.php`;

  let upstream: Response;
  try {
    upstream = await fetch(target, {
      method: "POST",
      headers: { Authorization: `Bearer ${session.token}` },
      body: form,
    });
  } catch {
    return NextResponse.json(
      { success: false, message: "Backend indisponible" },
      { status: 502 },
    );
  }

  const body = await upstream.text();
  return new NextResponse(body, {
    status: upstream.status,
    headers: {
      "Content-Type":
        upstream.headers.get("content-type") ?? "application/json",
    },
  });
}
