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

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

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

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

    async function retry() {
      retrying.value = true

      try {
        const ok = await checkBackendHealth({ force: true })
        if (ok) {
          await router.replace(loggedIn.value ? resolveEntryRoute() : { name: 'login' })
        }
      } finally {
        retrying.value = false
      }
    }

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