import { ref } from 'vue'
import { reflectionApi } from '@/api/reflection'
import { listSites } from '@/api/projection'

export interface SimpleLiteSiteOption {
  id: string
  name: string
  label: string
}

export async function fetchSimpleLiteSites(): Promise<SimpleLiteSiteOption[]> {
  try {
    const rows = await reflectionApi.listObjects('site')
    if (rows.length > 0) {
      return rows
        .map((s) => ({
          id: String(s.id),
          name: s.name || '',
          label: `#${s.id} ${s.name || '站点'}`
        }))
        .sort((a, b) => Number(a.id) - Number(b.id) || a.name.localeCompare(b.name))
    }
  } catch {
    /* 回退 projection API */
  }
  const rows = await listSites()
  return rows
    .map((s) => ({
      id: String(s.id),
      name: s.name || '',
      label: `#${s.id} ${s.name || '站点'}`
    }))
    .sort((a, b) => Number(a.id) - Number(b.id) || a.name.localeCompare(b.name))
}

export function useSimpleLiteSites() {
  const sites = ref<SimpleLiteSiteOption[]>([])
  const loading = ref(false)
  const loadError = ref('')

  async function load() {
    loading.value = true
    loadError.value = ''
    try {
      sites.value = await fetchSimpleLiteSites()
    } catch (e) {
      loadError.value = e instanceof Error ? e.message : '加载 SimpleLite 站点失败'
      sites.value = []
    } finally {
      loading.value = false
    }
  }

  return { sites, loading, loadError, load }
}
