import { defineStore } from 'pinia'
import { ref } from 'vue'
import { postForm } from '@/utils/request'

// 后端 API: POST uc/ancillary/system/app/version/{platform}
// platform 约定: 0 = Android, 1 = iOS
export type AppPlatform = 0 | 1

export interface AppVersion {
  id: string
  publishTime: string
  remark: string
  /** 最新版本号（接口字段名为 version） */
  newVersion: string
  /** 安装包下载链接（接口字段名为 downloadUrl） */
  downloadUrl: string
  platform: string
  /** 最低支持版本（用于强制更新判断） */
  lowestVersion: string
  /** 更新说明 */
  updateDescription: string
}

interface VersionApiItem {
  id?: string | number
  publishTime?: string
  remark?: string
  version?: string
  downloadUrl?: string
  platform?: string | number
  lowestVersion?: string
  updateDescription?: string
}

function mapVersion(r: VersionApiItem | null | undefined): AppVersion | null {
  if (!r || typeof r !== 'object') return null
  return {
    id: r.id != null ? String(r.id) : '',
    publishTime: r.publishTime ?? '',
    remark: r.remark ?? '',
    newVersion: r.version ?? '',
    downloadUrl: r.downloadUrl ?? '',
    platform: r.platform != null ? String(r.platform) : '',
    lowestVersion: r.lowestVersion ?? '',
    updateDescription: r.updateDescription ?? '',
  }
}

export const useAppVersionStore = defineStore('appVersion', () => {
  const android = ref<AppVersion | null>(null)
  const ios = ref<AppVersion | null>(null)
  const loading = ref(false)
  const error = ref('')

  async function fetchVersion(platform: AppPlatform) {
    try {
      const res = await postForm<VersionApiItem>(`uc/ancillary/system/app/version/${platform}`)
      return mapVersion(res)
    } catch (e) {
      // 单端失败不影响另一端
      if (!error.value) {
        error.value = e instanceof Error ? e.message : '获取版本信息失败'
      }
      return null
    }
  }

  async function fetchAll() {
    loading.value = true
    error.value = ''
    try {
      const [androidRes, iosRes] = await Promise.all([
        fetchVersion(0),
        fetchVersion(1),
      ])
      android.value = androidRes
      ios.value = iosRes
    } finally {
      loading.value = false
    }
  }

  return {
    android,
    ios,
    loading,
    error,
    fetchAll,
    fetchVersion,
  }
})
