import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import {
  AUTH_COOKIE_NAME,
  isLegacyDevMockToken,
  unauthorizedWithClearedCookie,
} from "@/lib/auth-cookie";
import { apiErrorResponse } from "@/lib/api-errors";
import { shouldFallbackToDevMock } from "@/lib/dev-api-mock";

export async function readAuthToken(req: NextRequest): Promise<string | undefined> {
  const jar = await cookies();
  return jar.get(AUTH_COOKIE_NAME)?.value;
}

export function rejectLegacyAuthToken(
  token: string | undefined,
  correlationId: string,
): NextResponse | null {
  if (token && !shouldFallbackToDevMock() && isLegacyDevMockToken(token)) {
    return unauthorizedWithClearedCookie(
      apiErrorResponse(
        401,
        "TOKEN_LEGACY",
        "Your session used the old dev mock. Please sign in again.",
        correlationId,
      ),
    );
  }
  return null;
}

export function clearCookieOnUnauthorized(
  response: NextResponse,
  upstreamStatus: number,
): NextResponse {
  if (upstreamStatus === 401) {
    return unauthorizedWithClearedCookie(response);
  }
  return response;
}
