import { nextTick } from "process";
import { ERRORENUM } from "../config/errorEnum";
import { TABLEENUM } from "../data/models/model";
import { findOnce } from "../data/select";
import { updateOneData } from "../data/update";

import { BizError } from "../util/bizError";

/**
 * 中间件 
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkUser(req, res, next) {
    if (!req.headers) req.headers = {};

    const reqToken = req.headers.token;
    const userId = req.headers.userid || "";

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

    let userInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!userInfo || !userInfo.userId) return next(new BizError(ERRORENUM.身份验证失败));
    
    if (userInfo.token != reqToken) return next(new BizError(ERRORENUM.身份验证过期));

    let checkToken = '';
    //30分钟更新token
    if ( (userInfo.tokenMs - new Date().valueOf()) >= (30 * 60 * 1000) ) {
        return next(new BizError(ERRORENUM.身份验证过期));
    } else {
        checkToken = reqToken;
        await updateOneData(TABLEENUM.用户表, {userId:userInfo.userId}, { tokenMs:new Date().valueOf()});
    }

    req.headers.userId = userId;
    req.headers.userInfo = {
        userId,
        isAdmin:userInfo.isAdmin
    }
    next();
}

export async function notCheck(req, res, next) {
    next();
}


/**
 * 中间件 数据维护接口
 * @param req 
 * @param res 
 * @param next 
 * @returns 
 */
export async function checkInterior(req, res, next) {
    if (!req.headers) req.headers = {};

    const Sign = req.headers.sign;

    let sysSign = 'sadfjslakdfjlksadjffujisdaiofjsajl09092302'
   
    if (!Sign || Sign != sysSign) return next(new BizError(ERRORENUM.非法登录, `内部接口非法调用 ${Sign}`));

    next();
}