import { useAuthStore } from '../stores/auth'
import { useMenuStore } from '../stores/menu'
import { buildAdminRoutesFromMenus } from './utils'
import { ROUTE_NAMES } from './index'

export function setupGuards(router) {
  router.beforeEach(async (to) => {
    const auth = useAuthStore()
    const menu = useMenuStore()

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

    if (!auth.token) {
      if (isAdminPath) return { path: '/login', query: { redirect: to.fullPath } }
      return true
    }

    if (!auth.meLoaded) {
      try {
        await auth.fetchMe()
      } catch (e) {
        const status = e?.response?.status
        if (status === 401 || status === 403) {
          auth.logout()
          menu.reset()
          if (isAuthPage) return true
          if (isAdminPath) return { path: '/login', query: { redirect: to.fullPath } }
          return true
        }
        throw e
      }
    }

    if (auth.roles.length === 0) {
      if (isAdminPath) return '/portal/home'
      return true
    }

    if (isAuthPage) return '/admin'

    if (isAdminPath && !menu.routesLoaded) {
      try {
        await menu.fetchMenus()
      } catch (e) {
        const status = e?.response?.status
        if (status === 401 || status === 403) {
          auth.logout()
          menu.reset()
          return { path: '/login', query: { redirect: to.fullPath } }
        }
        throw e
      }
      const adminRoutes = buildAdminRoutesFromMenus(menu.menuTree)
      for (const r of adminRoutes) router.addRoute(ROUTE_NAMES.AdminLayout, r)
      menu.routesLoaded = true
      return { ...to, replace: true }
    }

    return true
  })
}

