import type { Router } from 'vue-router'
import { useSiteSettings } from '@/composables/use-site-settings'

const INSTALL_CACHE_KEY = 'app_installed'
const INSTALL_CACHE_EXPIRY = 24 * 60 * 60 * 1000

function getCachedInstallStatus(): boolean | null {
  try {
    const cached = localStorage.getItem(INSTALL_CACHE_KEY)
    if (cached) {
      const { installed, timestamp } = JSON.parse(cached)
      if (Date.now() - timestamp < INSTALL_CACHE_EXPIRY) {
        return installed
      }
    }
  }
  catch {
    return null
  }
  return null
}

function setCachedInstallStatus(installed: boolean) {
  try {
    localStorage.setItem(INSTALL_CACHE_KEY, JSON.stringify({
      installed,
      timestamp: Date.now(),
    }))
  }
  catch {
  }
}

export function resetInstallCheck() {
  localStorage.removeItem(INSTALL_CACHE_KEY)
}

async function checkInstallStatus(): Promise<boolean> {
  const cached = getCachedInstallStatus()
  if (cached !== null) return cached

  try {
    const res = await fetch('/api/install/status')
    const data = await res.json()
    const installed = data?.data?.installed ?? false
    setCachedInstallStatus(installed)
    return installed
  }
  catch {
    setCachedInstallStatus(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'
    }
  })

  // 设置页面标题
  router.afterEach((to) => {
    const { siteSettings, getPageTitle } = useSiteSettings()
    const pageTitle = to.meta?.title as string | undefined
    document.title = getPageTitle(pageTitle)
  })
}
