import { NextRequest, NextResponse } from "next/server";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";
import {
  storePartnerInquiry,
  type PartnerInquiryPayload,
} from "@/lib/partner-inquiry-store";
import { fetchUpstream } from "@/lib/proxy-upstream";

export async function POST(req: NextRequest) {
  const correlationId = getOrCreateCorrelationId(req);

  let body: PartnerInquiryPayload;
  try {
    body = await req.json();
  } catch {
    return apiErrorResponse(400, "BAD_REQUEST", "Invalid JSON body", correlationId);
  }

  const { name, organization, email, role, message } = body;
  if (!name?.trim() || !organization?.trim() || !email?.trim() || !role?.trim()) {
    return apiErrorResponse(
      400,
      "BAD_REQUEST",
      "name, organization, email, and role are required",
      correlationId,
    );
  }

  const payload: PartnerInquiryPayload = {
    name: name.trim(),
    organization: organization.trim(),
    email: email.trim(),
    role: role.trim(),
    message: message?.trim() || undefined,
  };

  const upstream = await fetchUpstream("/partner/inquiries", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    correlationId,
  });

  if (upstream?.ok) {
    const data = await upstream.json().catch(() => ({ success: true }));
    return withCorrelationId(NextResponse.json(data, { status: upstream.status }), correlationId);
  }

  const inquiryId = storePartnerInquiry(payload);

  return withCorrelationId(
    NextResponse.json(
      {
        success: true,
        inquiryId,
        message: "Inquiry received. Our partnerships team will be in touch within 2 business days.",
      },
      { status: 201 },
    ),
    correlationId,
  );
}
