import { NextRequest, NextResponse } from "next/server";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";
import { handleDevReferenceOptions, shouldFallbackToDevMock } from "@/lib/dev-api-mock";
import { fetchUpstream } from "@/lib/proxy-upstream";

export async function GET(req: NextRequest) {
  const correlationId = getOrCreateCorrelationId(req);
  const { searchParams } = new URL(req.url);
  const query = searchParams.toString();
  const path = query ? `/reference/options?${query}` : "/reference/options";

  if (shouldFallbackToDevMock()) {
    const result = handleDevReferenceOptions(searchParams);
    return withCorrelationId(NextResponse.json(result.data, { status: result.status }), correlationId);
  }

  const upstream = await fetchUpstream(path, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
    correlationId,
  });

  if (!upstream && shouldFallbackToDevMock()) {
    const result = handleDevReferenceOptions(searchParams);
    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);
}
