import { ERRORENUM } from "../config/errorEnum";
import { systemConfig } from "../config/serverConfig";
import { EccTableConfig } from "../config/mongoTableConfig";
import { BizError } from "../util/bizError";
import { mysqlModelMap } from "../model/sqlModelBind";
import { selectOneDataByParam } from "../data/findData";
import { TABLENAME } from "../config/dbEnum";

/**
 * 中间件 校验连接对象token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkMongoSign(req, res, next) {
    if (!req.headers) req.headers = {};

    let sign = req.headers.sign;
    let table = req.headers.table;

    if (sign != systemConfig.sign) return next( new BizError(ERRORENUM.身份验证失败, `传入的sign值为:${sign}`) );
    if (!table) return next( new BizError(ERRORENUM.缺少必要参数_表名, `传入的table值为:${table}`) );
    
    if (!EccTableConfig[table]) return next( new BizError(ERRORENUM.不存在表, `传入的table值为:${table}`) );
    next();
}


/**
 * 中间件 校验连接对象token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkMySqlSign(req, res, next) {
    if (!req.headers) req.headers = {};

    let sign = req.headers.sign;
    let table = req.headers.table;

    if (sign != systemConfig.sign) return next( new BizError(ERRORENUM.身份验证失败, `传入的sign值为:${sign}`) );
    if (!table) return next( new BizError(ERRORENUM.缺少必要参数_表名, `传入的table值为:${table}`) );
    
    if (!mysqlModelMap[table]) return next( new BizError(ERRORENUM.不存在表, `传入的table值为:${table}`) );
    req.tableModel = mysqlModelMap[table];

    next();
}


/**
 * 中间件 校验用户登录token
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkUser(req, res, next) {
    if (!req.headers) req.headers = {};
    const userId = req.headers.userid || "";
    const reqToken = req.headers.token || "";
    const roleToken = req.headers.roletoken || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));
    
    let userProfileData: any = await selectOneDataByParam(TABLENAME.用户信息表, { 
        user_id: userId,
        token: reqToken 
    }, ["user_id", "roles", "current_role", "role_token", "permission", "token", "token_ms"]);
    
    if (!userProfileData || !userProfileData.data || !userProfileData.data.user_id) {
        return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    }

    if (userProfileData.data.token != reqToken) {
        return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId}`));
    }
    
    // 如果有roleToken，验证角色token
    if (roleToken && userProfileData.data.role_token != roleToken) {
        return next(new BizError(ERRORENUM.身份验证失败, `角色token无效`));
    }

    req.userInfo = {
        userId: userId,
        userName: req.headers.username || "",
        token: reqToken,
        roleToken: roleToken,
        roles: userProfileData.data.roles || "",
        currentRole: userProfileData.data.current_role || null,
        permission: userProfileData.data.permission || 0
    };

    next();
}

/**
 * 中间件 校验管理员权限（简化版）
 */
export async function checkAdmin(req, res, next) {
    try {
        const userInfo = req.userInfo;
        
        if (!userInfo || !userInfo.userId) {
            return next(new BizError(ERRORENUM.身份验证失败, '用户未登录'));
        }

        // 检查permission字段
        if (userInfo.permission !== 1) {
            return next(new BizError(ERRORENUM.权限不足, '需要管理员权限'));
        }

        next();
    } catch (error) {
        next(new BizError(ERRORENUM.系统繁忙请稍后重试, error.message));
    }
}




