import "server-only";
import { cookies, headers } from "next/headers";
import { auth } from "@/lib/auth";
import { isLocale, type Locale } from "./config";
import { negotiateAcceptLanguage } from "./negotiate";

export const LOCALE_COOKIE = "NEXT_LOCALE";

export async function getUserLocale(): Promise<Locale> {
  // The cookie holds the user's most RECENT explicit choice and must win over the
  // session. Better Auth caches the session (incl. user.locale) in a 5-min signed
  // cookie (session.cookieCache), so right after setUserLocale() the session still
  // reports the stale locale; the fresh NEXT_LOCALE cookie reflects the new choice
  // immediately. setUserLocale() writes both, so they only diverge during that window.
  const cookieLocale = (await cookies()).get(LOCALE_COOKIE)?.value;
  if (isLocale(cookieLocale)) return cookieLocale;

  const session = await auth.api.getSession({ headers: await headers() });
  const sessionLocale = (session?.user as { locale?: string } | undefined)
    ?.locale;
  if (isLocale(sessionLocale)) return sessionLocale;

  return negotiateAcceptLanguage((await headers()).get("accept-language"));
}
