import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { decodeAdminToken, ADMIN_COOKIE } from "@/lib/admin-auth";
import { adminApiUsesMock, getAdminCase } from "@/lib/admin-mock";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";
import { fetchUpstream } from "@/lib/proxy-upstream";

type RouteContext = { params: Promise<{ id: string }> };

export async function GET(req: NextRequest, context: RouteContext) {
  const correlationId = getOrCreateCorrelationId(req);
  const { id } = await context.params;
  const jar = await cookies();
  const officer = decodeAdminToken(jar.get(ADMIN_COOKIE)?.value);

  if (!officer) {
    return apiErrorResponse(401, "UNAUTHORIZED", "Officer authentication required", correlationId);
  }

  if (adminApiUsesMock()) {
    const detail = getAdminCase(id, officer);
    if (!detail) {
      return apiErrorResponse(404, "NOT_FOUND", "Case not found", correlationId);
    }
    return withCorrelationId(NextResponse.json({ case: detail }), correlationId);
  }

  const upstream = await fetchUpstream(`/admin/cases/${id}`, {
    method: "GET",
    headers: { Authorization: `Bearer ${jar.get(ADMIN_COOKIE)?.value}` },
    correlationId,
  });

  if (!upstream?.ok) {
    const fallback = getAdminCase(id, officer);
    if (fallback) {
      return withCorrelationId(NextResponse.json({ case: fallback }), correlationId);
    }
    return apiErrorResponse(upstream?.status ?? 404, "NOT_FOUND", "Case not found", correlationId);
  }

  const data = await upstream.json();
  return withCorrelationId(NextResponse.json(data), correlationId);
}
