
import { ERRORENUM } from "../config/errorEnum";
import { findUserInfoByUserId } from "../data/users";
import { BizError } from "../util/bizError";


/**
 * 小程序中间件
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkUserToken(req, res, next) {
    console.log(req.originalUrl, JSON.stringify(req.body));
    if (!req.headers) req.headers = {};
    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));

    let userInfo = await findUserInfoByUserId(userId);
    if (!userInfo) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
    if (userInfo.token != reqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${userId} token:${reqToken}`));

    req.userInfo = {
        userId:userInfo.userId,
        name:userInfo.name,
        position:userInfo.position
    }

    next();
}


/**
 * 管理后台中间件
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkAdminUserToken(req, res, next) {
    console.log(req.originalUrl, JSON.stringify(req.body));
    if (!req.headers) req.headers = {};
    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

    if (!userId) return next(new BizError(ERRORENUM.身份验证失败, `userId:${userId} token:${reqToken}`));

    let userInfo = await findUserInfoByUserId(userId);
    if (!userInfo) return next(new BizError(ERRORENUM.非法登录, `userId:${userId} token:${reqToken}`));
    
    if (userInfo.adminToken != reqToken ) return next(new BizError(ERRORENUM.身份验证过期, `userId:${userId} token:${reqToken}`));

    req.userInfo = {
        userId:userInfo.userId,
        name:userInfo.name,
        position:userInfo.position
    }

    next();
}
