/**
 * Vue Router 配置
 * 路由守卫：
 *   1. 未登录 → 跳 /login
 *   2. 有 Token 无用户信息 → 调 GET /api/auth/me 拉取
 *   3. 已登录访问 /login → 跳首页
 */

import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'
import Layout from '@/layout/index.vue'

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: { requiresAuth: false },
    },
    {
        path: '/',
        component: Layout,
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                name: 'Dashboard',
                component: () => import('@/views/dashboard/index.vue'),
                meta: { title: '工作台' },
            },
            {
                path: 'customers',
                name: 'Customers',
                component: () => import('@/views/customers/index.vue'),
                meta: { title: '客户管理' },
            },
            {
                path: 'customers/detail',
                name: 'CustomerDetail',
                component: () => import('@/views/customers/CustomerDetail.vue'),
                meta: { title: '客户档案' },
            },
            {
                path: 'orders',
                name: 'Orders',
                component: () => import('@/views/orders/index.vue'),
                meta: { title: '订单管理' },
            },
            {
                path: 'shipping',
                name: 'Shipping',
                component: () => import('@/views/shipping/index.vue'),
                meta: { title: '发货记录' },
            },
            {
                path: 'products',
                name: 'Products',
                component: () => import('@/views/products/index.vue'),
                meta: { title: '产品与库存' },
            },
            {
                path: 'finance',
                name: 'Finance',
                component: () => import('@/views/finance/index.vue'),
                meta: { title: '报销大盘' },
            },
            {
                path: 'settings',
                name: 'Settings',
                component: () => import('@/views/settings/index.vue'),
                meta: { title: '权限与员工管理' },
            },
            {
                path: 'logs',
                name: 'SalesLogs',
                component: () => import('@/views/logs/index.vue'),
                meta: { title: '销售日志' },
            },
            {
                path: 'reports',
                name: 'MonthlyReport',
                component: () => import('@/views/dashboard/MonthlyReport.vue'),
                meta: { title: 'AI 智能复盘' },
            },
            {
                path: 'finance/sales-invoices',
                name: 'SalesInvoices',
                component: () => import('@/views/finance/SalesInvoice.vue'),
                meta: { title: '销项发票' },
            },
        ],
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 白名单（免鉴权路由）
const WHITE_LIST = ['Login']

// ---- 全局前置守卫 ----
router.beforeEach(async (to: any, _from: any, next: any) => {
    const userStore = useUserStore()

    // 已登录
    if (userStore.isLoggedIn) {
        if (to.name === 'Login') {
            // 已登录还访问登录页 → 跳首页
            next({ name: 'Dashboard' })
            return
        }

        // 有 Token 但还没拉取用户信息 → 调 /auth/me
        if (!userStore.userInfo) {
            try {
                await userStore.fetchUserInfo()
                console.log('[Auth Guard] 用户信息已获取:', {
                    username: userStore.username,
                    dataScope: userStore.dataScope,
                    menuKeys: userStore.menuKeys,
                })
                next({ ...to, replace: true })
            } catch {
                // Token 过期或无效 → 清除并跳登录
                userStore.logout()
                next({ name: 'Login', query: { redirect: to.fullPath } })
            }
            return
        }

        next()
        return
    }

    // 未登录
    if (WHITE_LIST.includes(to.name as string)) {
        next()
    } else {
        next({ name: 'Login', query: { redirect: to.fullPath } })
    }
})

export default router
