// src/lib/sites/active-site.ts — active site selection backed by a cookie (server-readable).
import "server-only";
import { cookies } from "next/headers";
import { ACTIVE_SITE_COOKIE } from "./active-site-client";

/** UI-chrome language; used when no site context is available (auth/public pages). */
export const DEFAULT_LANGUAGE = "fr";

/** Validated active site id: the cookie value if it's a real site, else the first. Pure. */
export function pickActiveSiteId(
  siteIds: string[],
  cookieVal: string | undefined,
): string {
  if (cookieVal && siteIds.includes(cookieVal)) return cookieVal;
  return siteIds[0] ?? "";
}

/** Active site id for this request, read from the cookie and validated against the org's sites. */
export async function getActiveSiteId(siteIds: string[]): Promise<string> {
  const cookieVal = (await cookies()).get(ACTIVE_SITE_COOKIE)?.value;
  return pickActiveSiteId(siteIds, cookieVal);
}

/** Language of the active site (else the first), or DEFAULT_LANGUAGE if none. Pure. */
export function pickActiveLanguage(
  sites: { id: string; primaryLanguage: string }[],
  activeId: string,
  fallback: string = DEFAULT_LANGUAGE,
): string {
  const site = sites.find((s) => s.id === activeId) ?? sites[0];
  return site?.primaryLanguage || fallback;
}
