/**
 * 路由拦截：未登录用户访问需登录页面时，自动跳转到登录页
 */
import type { Router } from 'uni-mini-router';
import { useUserStore } from '@/state/modules/user';
import { getCache } from '@/utils/cache';
import { getStoredRole } from '@/utils/roleHome';

// 免登录白名单（路由 name）
const whiteList = ['home', 'login'];

export function userRouternext(router: Router) {
    router.beforeEach((to, _from, next) => {
        const userStore = useUserStore();

        if (userStore.isLogin) {
            const currentRole = getCache('role');
            const targetRole = (to as any).meta?.role;
            if (currentRole && to.name === 'home') {
                const homeName = currentRole === 'teacher'
                    ? 'teacher-home'
                    : currentRole === 'parent'
                        ? 'parent-home'
                        : 'home';
                if (homeName !== 'home') {
                    return next({ name: homeName });
                }
            }
            if (targetRole && currentRole && targetRole !== currentRole) {
                const homeName = currentRole === 'teacher'
                    ? 'teacher-home'
                    : currentRole === 'parent'
                        ? 'parent-home'
                        : 'home';
                return next({ name: homeName });
            }
            return next();
        }
        if (whiteList.includes(String(to.name))) {
            return next();
        }
        // 未登录跳转到登录页，并保留目标地址
        return next({
            name: 'login',
            query: { redirect: to.fullPath || (to.name as string) },
        });
    });

    router.afterEach((to) => {
        const userStore = useUserStore();
        // 401 清缓存后 Pinia 可能仍短暂为已登录，需同时校验本地 token
        if (userStore.isLogin && getCache('token') && to?.name === 'login') {
            const role = getStoredRole();
            if (!role) return;
            const homeName = role === 'teacher' ? 'teacher-home' : role === 'parent' ? 'parent-home' : 'home';
            router.replaceAll({ name: homeName });
        }
    });
}
