import { NextRequest, NextResponse } from "next/server";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";
import { handleDevCountryConfig, shouldFallbackToDevMock } from "@/lib/dev-api-mock";
import { fetchUpstream } from "@/lib/proxy-upstream";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ code: string }> },
) {
  const { code } = await params;
  const correlationId = getOrCreateCorrelationId(req);

  if (shouldFallbackToDevMock()) {
    const result = handleDevCountryConfig(code);
    return withCorrelationId(
      NextResponse.json(result.data, { status: result.status }),
      correlationId,
    );
  }

  const upstream = await fetchUpstream(`/config/country/${code}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
    correlationId,
  });

  if (!upstream && shouldFallbackToDevMock()) {
    const result = handleDevCountryConfig(code);
    return withCorrelationId(
      NextResponse.json(result.data, { status: result.status }),
      correlationId,
    );
  }

  if (!upstream) {
    return apiErrorResponse(503, "SERVICE_UNAVAILABLE", "Backend service unavailable", correlationId);
  }

  const data = await upstream.json().catch(() => ({}));
  return withCorrelationId(
    NextResponse.json(data, { status: upstream.status }),
    correlationId,
  );
}
