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

const publicApiUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://admin.localhost";
const localDockerApiUrl = publicApiUrl.includes("admin.localhost") ? "http://nginx" : publicApiUrl;
const serverApiBaseUrl = process.env.SERVER_API_URL ?? localDockerApiUrl;
const serverApiHost = process.env.SERVER_API_HOST ?? (publicApiUrl.includes("admin.localhost") ? "admin.localhost" : undefined);

export async function POST(request: NextRequest) {
  try {
    const payload = await request.json();
    const response = await fetch(`${serverApiBaseUrl}/api/v1/contact`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        ...(serverApiHost ? { Host: serverApiHost } : {}),
      },
      body: JSON.stringify(payload),
    });

    const body = await response.json();

    return NextResponse.json(body, { status: response.status });
  } catch {
    return NextResponse.json(
      {
        success: false,
        message: "Contact service is currently unavailable.",
      },
      { status: 503 },
    );
  }
}
