import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { useBackendHealth } from '../../composables/useBackendHealth.js'
import { useSystemState } from '../../composables/useSystemState.js'

const AUTO_RECOVER_INTERVAL_MS = 1500

export default {
  name: 'BackendUnavailableRouteView',
  setup() {
    const router = useRouter()
    const { backendChecking, backendError, checkBackendHealth } = useBackendHealth()
    const { loggedIn, resolveEntryRoute } = useSystemState()
    const retrying = ref(false)
    let autoRecoverTimer = 0
    let autoRecovering = false

    const statusMessage = computed(() => {
      return backendError.value || '后端服务尚未就绪，请先检查 FastAPI 和数据库连接。'
    })

    async function navigateToAvailableRoute() {
      await router.replace(loggedIn.value ? resolveEntryRoute() : { name: 'login' })
    }

    function stopAutoRecover() {
      if (!autoRecoverTimer) {
        return
      }

      globalThis.clearInterval(autoRecoverTimer)
      autoRecoverTimer = 0
    }

    async function recoverWhenBackendReady() {
      if (autoRecovering) {
        return
      }

      autoRecovering = true

      try {
        const ok = await checkBackendHealth({ force: true })
        if (ok) {
          stopAutoRecover()
          await navigateToAvailableRoute()
        }
      } finally {
        autoRecovering = false
      }
    }

    function startAutoRecover() {
      stopAutoRecover()
      void recoverWhenBackendReady()
      autoRecoverTimer = globalThis.setInterval(() => {
        void recoverWhenBackendReady()
      }, AUTO_RECOVER_INTERVAL_MS)
    }

    async function retry() {
      retrying.value = true

      try {
        const ok = await checkBackendHealth({ force: true })
        if (ok) {
          stopAutoRecover()
          await navigateToAvailableRoute()
        }
      } finally {
        retrying.value = false
      }
    }

    onMounted(() => {
      startAutoRecover()
    })

    onBeforeUnmount(() => {
      stopAutoRecover()
    })

    return {
      backendChecking,
      retrying,
      statusMessage,
      retry
    }
  }
}
