import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getModelList } from '@/api/modules/model'
import type { ModelItem } from '@/types'

/**
 * 模型列表缓存 store
 * 列表页根据 base_model id 渲染模型名时使用
 */
export const useModelsStore = defineStore('models', () => {
  const list = ref<ModelItem[]>([])
  const loaded = ref(false)
  let pendingLoad: Promise<void> | null = null

  async function load(force = false) {
    if (loaded.value && !force) return
    if (pendingLoad && !force) return pendingLoad

    pendingLoad = (async () => {
      try {
        list.value = (await getModelList()) || []
        loaded.value = true
      } catch {
        list.value = []
      } finally {
        pendingLoad = null
      }
    })()

    return pendingLoad
  }

  /** 根据 id 获取模型名 */
  function getModelName(modelId: string | number): string {
    if (!modelId) return '-'
    const model = list.value.find(
      (m) => m.id == modelId || m.id === String(modelId) || m.id === Number(modelId),
    )
    return model ? model.name : `模型${modelId}`
  }

  return { list, loaded, load, getModelName }
})
