import { ref } from 'vue'

const regions = ref<{ id: number, region_name: string }[]>([])
const isLoadingRegions = ref(true)
const regionsError = ref<string | null>(null)
let hasFetchedRegions = false
let isFetchRegionsInProgress = false

const normalizeRegions = (value: unknown): { id: number, region_name: string }[] | null => {
  if (!Array.isArray(value)) return null
  const seen = new Set<string>()
  const normalized: { id: number, region_name: string }[] = []
  for (const item of value) {
    if (!item || typeof item !== 'object') continue
    const record = item as { id?: unknown, region_name?: unknown }
    const name = typeof record.region_name === 'string' ? record.region_name.trim() : ''
    if (!name || seen.has(name) || typeof record.id !== 'number') continue
    seen.add(name)
    normalized.push({ id: record.id, region_name: name })
  }
  return normalized
}

export const useDashboardRegions = () => {
  const fetchRegions = async (force = false) => {
    if ((!force && hasFetchedRegions) || isFetchRegionsInProgress) return
    isFetchRegionsInProgress = true
    isLoadingRegions.value = true
    regionsError.value = null
    try {
      const api = useApi()
      const data = await api.post('v3/dashboard/region', {})
      const normalized = normalizeRegions(data?.data)
      if (!normalized) throw new Error('Region response invalid')
      regions.value = normalized
      hasFetchedRegions = true
    } catch (error) {
      regions.value = []
      regionsError.value = 'Region options unavailable'
      hasFetchedRegions = false
    } finally {
      isFetchRegionsInProgress = false
      isLoadingRegions.value = false
    }
  }
  return { regions, isLoadingRegions, regionsError, fetchRegions }
}
