import { ref } from 'vue'

const lgus = ref<{ id: number, municipality_name: string }[]>([])
// The first render must reserve the selector/table space until the client fetch starts.
const isLoadingLgus = ref(true)
// When the fetch fails we surface a friendly error (shown by dropdown placeholders)
// instead of silently leaving the list empty.
const lgusError = ref<string | null>(null)
let hasFetched = false
// Dedup guard: several components call fetchLgus() at the same time (page + filters).
// This flag prevents a second concurrent request while one is already in flight.
let isFetchInProgress = false

// Coerce the raw API payload into clean {id, municipality_name} rows:
// drops invalid rows, trims names, and removes duplicates by name.
const normalizeLgus = (value: unknown): { id: number, municipality_name: string }[] | null => {
  if (!Array.isArray(value)) return null

  const seen = new Set<string>()
  const normalized: { id: number, municipality_name: string }[] = []

  for (const item of value) {
    if (!item || typeof item !== 'object') continue

    const record = item as { id?: unknown, municipality_name?: unknown }
    const name = typeof record.municipality_name === 'string' ? record.municipality_name.trim() : ''

    if (!name || seen.has(name) || typeof record.id !== 'number') continue
    seen.add(name)
    normalized.push({ id: record.id, municipality_name: name })
  }

  normalized.sort((a, b) => a.municipality_name.localeCompare(b.municipality_name))
  return normalized
}

export const useDashboardLgus = () => {
  // force=true bypasses the cache so the UI can offer a manual "Retry".
  const fetchLgus = async (force = false) => {
    if ((!force && hasFetched) || isFetchInProgress) return
    isFetchInProgress = true
    isLoadingLgus.value = true
    lgusError.value = null

    try {
      const api = useApi()
      const data = await api.post('v3/dashboard/municipality', {})
      const normalized = normalizeLgus(data?.data)

      if (!normalized) {
        throw new Error('Municipality response does not match the expected data shape')
      }

      lgus.value = normalized
      hasFetched = true
    } catch (error) {
      // On failure: empty the list, flag the error, and reset the cache so a
      // later Retry will actually re-fetch instead of being skipped.
      lgus.value = []
      lgusError.value = 'LGU options unavailable'
      hasFetched = false
      console.error('Failed to fetch LGUs:', error)
    } finally {
      isFetchInProgress = false
      isLoadingLgus.value = false
    }
  }

  return {
    lgus,
    isLoadingLgus,
    lgusError,
    fetchLgus
  }
}
