// src/lib/sites/site-language.ts — resolves the document language from the active site.
import "server-only";
import { headers } from "next/headers";
import { auth } from "@/lib/auth";
import {
  DEFAULT_LANGUAGE,
  getActiveSiteId,
  pickActiveLanguage,
} from "./active-site";
import { getSitesForOrg } from "./queries";

/**
 * The document language for this request: the active site's configured
 * `primaryLanguage`. Runs in the ROOT layout, so it must NEVER throw — it reads
 * the session's `activeOrganizationId` DIRECTLY (not via getActiveOrgId, which
 * self-heals and HARD-THROWS for an orgless account; that throw escaped the
 * try/catch below through the React `cache()` wrapper and 500'd every page).
 * Orgless accounts — every SYS operator (Admin/Staff SYS) and normal users
 * mid-bootstrap — have no site language, so they fall back to DEFAULT_LANGUAGE
 * and `<html lang>` stays sane.
 */
export async function getActiveSiteLanguage(): Promise<string> {
  try {
    const session = await auth.api.getSession({ headers: await headers() });
    const orgId = session?.session.activeOrganizationId;
    if (!orgId) return DEFAULT_LANGUAGE;
    const sites = await getSitesForOrg(orgId);
    if (sites.length === 0) return DEFAULT_LANGUAGE;
    const activeId = await getActiveSiteId(sites.map((s) => s.id));
    return pickActiveLanguage(sites, activeId);
  } catch {
    return DEFAULT_LANGUAGE;
  }
}
