import { NextResponse } from "next/server";

const CMS_BASE_URL = process.env.NEXT_PUBLIC_CMS_BASE_URL || "";

export async function POST(request: Request) {
  if (!CMS_BASE_URL) {
    return NextResponse.json(
      { error: "Missing NEXT_PUBLIC_CMS_BASE_URL on server." },
      { status: 500 },
    );
  }

  const bodyText = await request.text();
  const url = `${CMS_BASE_URL.replace(/\/$/, "")}/api/form-submissions`;

  try {
    const res = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: bodyText,
    });

    const contentType = res.headers.get("content-type") || "application/json";
    const responseBody = await res.text();

    return new NextResponse(responseBody, {
      status: res.status,
      headers: {
        "Content-Type": contentType,
      },
    });
  } catch (err) {
    console.error("[landing api] form-submissions proxy failed:", err);
    return NextResponse.json(
      { error: "Failed to reach CMS form-submissions endpoint." },
      { status: 502 },
    );
  }
}
