import {
  DEFAULT_LANGUAGE,
  isAppLanguage,
  LANGUAGE_COOKIE,
  normalizeAppLanguage,
  type AppLanguage,
} from "./registry";
import type { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
import { resolveLanguageFromAcceptHeader } from "./resolveLanguage";

export {
  DEFAULT_LANGUAGE,
  ENABLED_LANGUAGES,
  getDirection,
  getLanguageDefinition,
  isAppLanguage,
  LANGUAGE_COOKIE,
  LANGUAGE_LABELS,
  LANGUAGE_REGISTRY,
  normalizeAppLanguage,
  SUPPORTED_LANGUAGES,
  type AppLanguage,
  type LanguageDefinition,
  type LanguageDirection,
} from "./registry";

export { syncDocumentLanguage } from "./syncDocumentLanguage";
export { shouldUseLtrLayout, LTR_WHEN_ENGLISH_PREFIXES } from "./pageDirection";

export {
  getSeoPage,
  getSiteSeoMeta,
  getListSeoTemplates,
  formatLocalizedSeoTitle,
  buildLocalizedLocationLabel,
  buildHreflangAlternates,
  interpolateTemplate,
} from "./seo";

export type { SeoPageKey, SeoPageMeta, SeoSiteMeta } from "./resources";

export function resolveLanguageFromCookieStore(
  cookieStore: Pick<ReadonlyRequestCookies, "get">
): AppLanguage {
  const cookieLang = cookieStore.get(LANGUAGE_COOKIE)?.value;
  return normalizeAppLanguage(cookieLang);
}

export {
  resolveLanguageFromLanguageTags,
  resolveLanguageFromAcceptHeader,
  resolveLanguageFromSingleTag,
} from "./resolveLanguage";

export {
  readStoredLanguagePreference,
  resolveBrowserLanguage,
  resolveClientLanguage,
  persistLanguagePreference,
} from "./clientLanguage";

/** Server-side locale for metadata, SSR, and SEO */
export function resolveServerLanguage(options: {
  cookieStore: Pick<ReadonlyRequestCookies, "get">;
  acceptLanguage?: string | null;
}): AppLanguage {
  const cookieValue = options.cookieStore.get(LANGUAGE_COOKIE)?.value;
  if (isAppLanguage(cookieValue)) {
    return normalizeAppLanguage(cookieValue);
  }

  const fromHeader = resolveLanguageFromAcceptHeader(options.acceptLanguage);
  if (fromHeader) return fromHeader;

  return DEFAULT_LANGUAGE;
}
