import { getCache } from '@/utils/cache';

export type UserRole = 'student' | 'teacher' | 'parent';

const VALID_ROLES: UserRole[] = ['student', 'teacher', 'parent'];

export const ROLE_HOME_URL: Record<UserRole, string> = {
    student: '/pages/index/index',
    teacher: '/pages/teacher/index/index',
    parent: '/pages/parent/home/index',
};

const isNonEmptyObject = (val: unknown) =>
    !!val && typeof val === 'object' && Object.keys(val as object).length > 0;

/** 读取本地已保存的账号类型 */
export const getStoredRole = (): UserRole | null => {
    const role = getCache('role');
    return VALID_ROLES.includes(role as UserRole) ? (role as UserRole) : null;
};

/** 是否具备可自动进入对应首页的本地登录态 */
export const hasStoredSession = (): boolean => {
    const token = getCache('token');
    const role = getStoredRole();
    if (!token || !role) return false;

    if (role === 'teacher') {
        return isNonEmptyObject(getCache('teacherInfo'));
    }
    return isNonEmptyObject(getCache('userInfo'));
};

/** 根据账号类型获取首页路径 */
export const getRoleHomeUrl = (role: UserRole | null = getStoredRole()) =>
    (role ? ROLE_HOME_URL[role] : ROLE_HOME_URL.student);

/**
 * 若本地已有 token、账号类型和用户信息，则跳转到对应角色首页
 * @returns 是否已触发跳转
 */
export const redirectToRoleHomeIfNeeded = (): boolean => {
    if (!hasStoredSession()) return false;

    const role = getStoredRole();
    if (!role) return false;

    const targetUrl = getRoleHomeUrl(role);
    const pages = getCurrentPages();
    const current = pages[pages.length - 1];
    if (current) {
        const route = `/${current.route}`;
        if (route === targetUrl) return false;
    }

    uni.reLaunch({ url: targetUrl });
    return true;
};
