import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";
import { decodeDevToken, handleDevFarmerDashboard, shouldFallbackToDevMock } from "@/lib/dev-api-mock";
import { fetchUpstream } from "@/lib/proxy-upstream";

const COOKIE_NAME = "agnet_token";

export async function GET(req: NextRequest) {
  const correlationId = getOrCreateCorrelationId(req);
  const jar = await cookies();
  const token = jar.get(COOKIE_NAME)?.value;

  if (!token) {
    return apiErrorResponse(401, "UNAUTHORIZED", "Unauthorized", correlationId);
  }

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${token}`,
  };

  if (shouldFallbackToDevMock()) {
    const user = decodeDevToken(token);
    if (!user) {
      return apiErrorResponse(401, "UNAUTHORIZED", "Unauthorized", correlationId);
    }
    const mock = handleDevFarmerDashboard(user.id);
    return withCorrelationId(NextResponse.json(mock.data, { status: mock.status }), correlationId);
  }

  const upstream = await fetchUpstream("/farmer/dashboard", {
    method: "GET",
    headers,
    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);
}
