import { parse } from 'accept-language-parser';
import { SUPPORTED_LOCALES } from '$lib/translations';

/**
 * A Set of all supported locale codes for quick validation.
 * Example values: "en-US", "pt-BR"
 * @type {Set<string>}
 */
const SUPPORTED_LOCALE_SET = new Set(Object.values(SUPPORTED_LOCALES));

/**
 * Extracts the best matching locale from an Accept-Language HTTP header.
 *
 * @param {string | null} header - The Accept-Language header value.
 * @returns {string | null} - A supported locale string like "en-US", or null if none matched.
 */
function localeFromHeader(header) {
  if (!header) return null;
  const parsed = parse(header);
  for (const { code, region } of parsed) {
    const locale = region ? `${code}-${region}` : code;
    if (SUPPORTED_LOCALE_SET.has(locale)) return locale;
  }
  return null;
}

/**
 * Server-side load function that returns the initial route and fallback language.
 * The language is inferred from the Accept-Language header.
 * `localStorage` will take precedence on the client.
 *
 * @type {import('@sveltejs/kit').ServerLoad}
 */
export async function load({ url, request }) {
  /** @type {string} */
  const route = url.pathname;

  /** @type {string} */
  const fallbackLanguage =
    localeFromHeader(request.headers.get('accept-language')) ||
    SUPPORTED_LOCALES.EN_US;

  return { fallbackLanguage, route };
}
