/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
import { pages, subPackages } from 'virtual:uni-pages'
import { fetchMiniMe } from '@/api/auth'
import { setUnauthorizedRedirectHandler } from './authRedirect'
import { clearMiniAuthSession, getPersistedAuthState, updateMiniAuthProfile } from '@/store/auth'
import { normalizeMeProfile } from '@/types/auth'

function generateRoutes() {
  const routes = pages.map((page) => {
    const newPath = `/${page.path}`
    return { ...page, path: newPath }
  })
  if (subPackages && subPackages.length > 0) {
    subPackages.forEach((subPackage) => {
      const subRoutes = subPackage.pages.map((page: any) => {
        const newPath = `/${subPackage.root}/${page.path}`
        return { ...page, path: newPath }
      })
      routes.push(...subRoutes)
    })
  }
  return routes
}

const router = createRouter({
  routes: generateRoutes(),
})

setUnauthorizedRedirectHandler(() => {
  router.replaceAll({ name: 'login' })
})

const PUBLIC_ROUTE_NAMES = new Set(['login', 'visitorCode'])
const HOME_ROUTE_NAME = 'home'

function isPublicRoute(name?: string) {
  return Boolean(name && PUBLIC_ROUTE_NAMES.has(name))
}

router.beforeEach((to, from, next) => {
  const state = getPersistedAuthState()
  const hasToken = Boolean(state.token)
  const hasProfile = Boolean(state.profile)
  const publicRoute = isPublicRoute(to.name)

  if (!hasToken) {
    if (publicRoute) {
      next()
      return
    }
    next({ name: 'login' })
    return
  }

  const ensureProfile = async () => {
    if (hasProfile) {
      return true
    }
    try {
      const profile = await fetchMiniMe()
      updateMiniAuthProfile(normalizeMeProfile(profile))
      return true
    }
    catch (error) {
      console.warn('mini auth guard fetch /me failed', error)
      clearMiniAuthSession()
      return false
    }
  }

  return Promise.resolve(ensureProfile()).then((ok) => {
    if (!ok) {
      next({ name: 'login' })
      return
    }
    if (publicRoute) {
      next({ name: HOME_ROUTE_NAME })
      return
    }
    next()
  })
})

router.afterEach((to, from) => {
  if (import.meta.env.MODE === 'development' && to.path) {
    console.log(`📄 页面切换完成: ${from.path || '-'} -> ${to.path}`)
  }
})

export default router
