import type { Router } from 'vue-router'

let installChecked = false
let isInstalled = false

async function checkInstallStatus(): Promise<boolean> {
  if (installChecked) return isInstalled
  try {
    const res = await fetch('/api/install/status')
    const data = await res.json()
    isInstalled = data?.data?.installed ?? false
    installChecked = true
    return isInstalled
  }
  catch {
    installChecked = true
    isInstalled = false
    return false
  }
}

export function createRouterGuard(router: Router) {
  router.beforeEach(async (to) => {
    if (to.path === '/install') {
      return true
    }

    const installed = await checkInstallStatus()
    if (!installed) {
      return '/install'
    }

    const token = localStorage.getItem('token')
    const userStr = localStorage.getItem('user')

    let user = null
    if (userStr) {
      try {
        user = JSON.parse(userStr)
      }
      catch (error) {
        console.error('Failed to parse user data:', error)
      }
    }

    const requiresAuth = to.path.startsWith('/admin') || to.path.startsWith('/agent')
    const isAuthPage = to.path === '/login' || to.path === '/register'

    if (requiresAuth && !token) {
      return { path: '/login', query: { redirect: to.fullPath } }
    }

    if (isAuthPage && token && user) {
      const redirect = (to.query.redirect as string) || ''
      if (redirect) {
        return redirect
      }
      if (user.role === 'agent' || user.parent_agent_id) {
        return '/agent'
      }
      return '/admin'
    }
  })
}
