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

/** @type {Set<string>} */
const SUPPORTED_LOCALE_SET = new Set(Object.values(SUPPORTED_LOCALES));

/**
 * @param {string | null} header
 * @returns {string | null}
 */
function localeFromHeader(header) {
  if (!header) return null;
  const parsed = parse(header);
  for (const { code, region } of parsed) {
    const loc = region ? `${code}-${region}` : code;
    if (SUPPORTED_LOCALE_SET.has(loc)) return loc;
  }
  return null;
}

/** @type {import('@sveltejs/kit').ServerLoad} */
export async function load({ url, request }) {
  const route = url.pathname;
  const fallbackLanguage =
    localeFromHeader(request.headers.get('accept-language')) ||
    SUPPORTED_LOCALES.EN_US;

  return { fallbackLanguage, route };
}
