import type { Locale } from "vue-i18n";
import { client, safeClient } from "@/api";

export interface Language {
  code: Locale;
  name: string;
  nativeName: string;
}

/**
 * 语言管理组合式函数
 */
export function useLanguage() {
  const { locale, availableLocales, mergeLocaleMessage } = useI18n();
  const language = useStorage<Locale>("app-language", locale.value);

  // 可用的语言列表
  const languages: Language[] = [
    {
      code: "zh-CN",
      name: "Chinese (Simplified)",
      nativeName: "简体中文",
    },
  ];

  // 当前语言
  const currentLanguage = computed(() => {
    return languages.find(lang => lang.code === locale.value) || languages[0];
  });

  /**
   * 切换语言
   */
  function setLanguage(langCode: Locale) {
    locale.value = langCode;
    language.value = langCode;
    loadRemoteLanguage();
  }

  function loadRemoteLanguage() {
    const storageKey = `remote-lang-${language.value}`;
    const remoteLangJson = useStorageCache<string>(storageKey, "", { ttl: 24 * 60 * 60 }); // 缓存 1 天
    if (remoteLangJson.value) {
      try {
        const messages = JSON.parse(remoteLangJson.value);
        mergeLocaleMessage(locale.value, messages);
        return;
      }
      catch (e) {
        console.error("Failed to parse remote language JSON:", e);
      }
    }
    safeClient(client.api.error_messages({ lang: language.value }).get()).then((res) => {
      clearExpiredCaches([storageKey]);
      remoteLangJson.value = JSON.stringify(res.data.value);
      mergeLocaleMessage(locale.value, res.data.value);
    });
  }

  /**
   * 从 localStorage 加载保存的语言
   */
  function loadSavedLanguage() {
    if (language.value && availableLocales.includes(language.value)) {
      locale.value = language.value;
      loadRemoteLanguage();
    }
  }

  return {
    languages,
    currentLanguage,
    locale,
    setLanguage,
    loadSavedLanguage,
  };
}
