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, handleDevFarmerPreferences, shouldFallbackToDevMock } from "@/lib/dev-api-mock";
import { fetchUpstream } from "@/lib/proxy-upstream";

const COOKIE_NAME = "agnet_token";

export async function PATCH(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 body = await req.json().catch(() => null);
  if (!body?.primaryLanguage) {
    return apiErrorResponse(400, "BAD_REQUEST", "primaryLanguage is required", correlationId);
  }

  if (shouldFallbackToDevMock()) {
    const user = decodeDevToken(token);
    if (!user) {
      return apiErrorResponse(401, "UNAUTHORIZED", "Unauthorized", correlationId);
    }
    const mock = handleDevFarmerPreferences(user.id, body);
    return withCorrelationId(NextResponse.json(mock.data, { status: mock.status }), correlationId);
  }

  const upstream = await fetchUpstream("/farmer/preferences", {
    method: "PATCH",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(body),
    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);
}
