import { createRouter, createWebHistory } from 'vue-router'
import StorePage from '../modules/store/StorePage.vue'
import AdminPage from '../modules/admin/AdminPage.vue'
import ProductDetail from '../modules/store/ProductDetail.vue'
import CheckoutPage from '../modules/store/CheckoutPage.vue'
import AuthCallback from '../modules/auth/AuthCallback.vue'
import MyOrdersPage from '../modules/user/MyOrdersPage.vue'
import MaintenancePage from '../modules/maintenance/MaintenancePage.vue'
import WishlistPage from '../modules/wishlist/WishlistPage.vue'
import { fetchSiteMaintenance } from '../modules/shared/api'

const BYPASS_ROUTES = ['/admin', '/auth/callback', '/maintenance', '/wishlist']

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'store', component: StorePage },
    { path: '/product/:id', name: 'product-detail', component: ProductDetail },
    { path: '/checkout/:id', name: 'checkout', component: CheckoutPage },
    { path: '/admin', name: 'admin', component: AdminPage },
    { path: '/auth/callback', name: 'auth-callback', component: AuthCallback },
    { path: '/my/orders', name: 'my-orders', component: MyOrdersPage },
    {
      path: '/maintenance',
      name: 'maintenance',
      component: MaintenancePage,
      props: (route) => ({ reason: route.query.reason || '' })
    },
    { path: '/wishlist', name: 'wishlist', component: WishlistPage }
  ]
})

router.beforeEach(async (to) => {
  if (BYPASS_ROUTES.some((p) => to.path.startsWith(p))) {
    return true
  }
  try {
    const { maintenance, reason } = await fetchSiteMaintenance()
    if (maintenance) {
      return { name: 'maintenance', query: { reason } }
    }
  } catch {
    // 接口异常时放行，不阻断用户
  }
  return true
})

export default router
