import { isSupportedLocale } from "./locales.ts";
import type { SupportedLocale } from "./types.ts";

export const localeStorageKey = "nianxx.locale";

type LocaleStorageLike = Pick<Storage, "getItem" | "setItem">;

function resolveStorage(storage?: LocaleStorageLike): LocaleStorageLike | undefined {
  if (storage) {
    return storage;
  }

  try {
    return globalThis.localStorage;
  } catch {
    return undefined;
  }
}

export function readStoredLocale(storage?: LocaleStorageLike): SupportedLocale | null {
  try {
    const locale = resolveStorage(storage)?.getItem(localeStorageKey);
    return isSupportedLocale(locale) ? locale : null;
  } catch {
    return null;
  }
}

export function writeStoredLocale(locale: SupportedLocale, storage?: LocaleStorageLike): void {
  try {
    resolveStorage(storage)?.setItem(localeStorageKey, locale);
  } catch {
    // Storage can be unavailable in private or embedded browser contexts.
  }
}
