export const isServerAvailable = ref(true)
export const isChecking = ref(false)
export const lastCheckTime = ref<Date | null>(null)

export function useServerHealth() {
  const checkInterval = ref<NodeJS.Timeout | null>(null)
  const healthCheckUrl = '/api/actuator/health'

  async function checkServerHealth(): Promise<boolean> {
    if (isChecking.value) return isServerAvailable.value

    isChecking.value = true
    lastCheckTime.value = new Date()

    try {
      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), 5000)

      const response = await fetch(healthCheckUrl, {
        method: 'GET',
        signal: controller.signal,
        headers: {
          'Content-Type': 'application/json'
        }
      })

      clearTimeout(timeoutId)

      const wasAvailable = isServerAvailable.value
      isServerAvailable.value = response.ok

      if (!wasAvailable && isServerAvailable.value) {
        console.info('Server is back online')
      }

      if (wasAvailable && !isServerAvailable.value) {
        console.warn('Server is no longer available')
      }

      return isServerAvailable.value
    } catch (error) {
      const wasAvailable = isServerAvailable.value
      isServerAvailable.value = false

      if (wasAvailable) {
        console.warn('Server health check failed:', error)
      }

      return false
    } finally {
      isChecking.value = false
    }
  }

  async function startPeriodicHealthCheck(intervalMs: number = 60000) {
    if (checkInterval.value) {
      clearInterval(checkInterval.value)
    }

    checkServerHealth()

    checkInterval.value = setInterval(() => {
      checkServerHealth()
    }, intervalMs)

    onUnmounted(() => {
      if (checkInterval.value) {
        clearInterval(checkInterval.value)
        checkInterval.value = null
      }
    })

    return checkInterval.value
  }

  const stopHealthCheck = () => {
    if (checkInterval.value) {
      clearInterval(checkInterval.value)
      checkInterval.value = null
    }
  }

  return {
    isServerAvailable,
    isChecking,
    lastCheckTime,
    healthCheckUrl,
    checkServerHealth,
    startPeriodicHealthCheck,
    stopHealthCheck
  }
}
