import {
  DEFAULT_LANGUAGE,
  ENABLED_LANGUAGES,
  getLanguageDefinition,
  isAppLanguage,
  type AppLanguage,
} from "./registry";

function tagMatchesLanguage(tag: string, code: AppLanguage): boolean {
  const normalized = tag.trim().toLowerCase();
  if (!normalized) return false;

  const def = getLanguageDefinition(code);
  return (
    normalized === code ||
    normalized.startsWith(`${code}-`) ||
    normalized === def.htmlLang ||
    normalized.startsWith(`${def.htmlLang}-`)
  );
}

/** Match the first supported language from a ordered list of BCP-47 tags */
export function resolveLanguageFromLanguageTags(
  tags: string[] | null | undefined
): AppLanguage | null {
  if (!tags?.length) return null;

  for (const rawTag of tags) {
    const tag = rawTag.split(";")[0]?.trim();
    if (!tag) continue;

    for (const code of ENABLED_LANGUAGES) {
      if (tagMatchesLanguage(tag, code)) {
        return code;
      }
    }
  }

  return null;
}

export function resolveLanguageFromAcceptHeader(
  acceptLanguage: string | null | undefined
): AppLanguage | null {
  if (!acceptLanguage) return null;

  const tags = acceptLanguage
    .split(",")
    .map((part) => part.split(";")[0]?.trim())
    .filter(Boolean) as string[];

  return resolveLanguageFromLanguageTags(tags);
}

export function resolveLanguageFromSingleTag(
  tag: string | null | undefined
): AppLanguage | null {
  if (!tag) return null;
  if (isAppLanguage(tag)) return tag;
  return resolveLanguageFromLanguageTags([tag]);
}
