/**
 * Client state + polling for the commission-system online indicator on the
 * commission pages. The server endpoint (/api/commission/system-status) applies
 * anti-flap hysteresis — this composable only mirrors its verdict.
 *
 * Optimistic default (online: true) so there is no false alarm while loading.
 * Call the composable inside <script setup> and use the returned closures from
 * timers/watchers — they capture the state ref, so no Nuxt-context issues.
 */

interface CommissionSystemStatus {
  online: boolean
  checkedAt: number
  degradedSince: number | null
}

// Module-level timer: shared across pages so polling never doubles up
let pollTimer: ReturnType<typeof setInterval> | null = null

export const useCommissionSystemStatus = () => {
  const status = useState<CommissionSystemStatus>('commissionSystemStatus', () => ({
    online: true,
    checkedAt: 0,
    degradedSince: null
  }))

  const refresh = async () => {
    if (typeof window === 'undefined') return
    try {
      const res: any = await $fetch('/api/commission/system-status')
      if (res && typeof res.online === 'boolean') {
        status.value = {
          online: res.online,
          checkedAt: res.checkedAt ?? Date.now(),
          degradedSince: res.degradedSince ?? null
        }
      }
    } catch {
      // keep last known state — a failed poll must not flip the indicator
    }
  }

  const startPolling = (intervalMs: number = 30_000) => {
    if (typeof window === 'undefined' || pollTimer) return
    refresh()
    pollTimer = setInterval(refresh, intervalMs)
  }

  const stopPolling = () => {
    if (pollTimer) {
      clearInterval(pollTimer)
      pollTimer = null
    }
  }

  return { status, refresh, startPolling, stopPolling }
}
