import { STATUS } from '@consts';
import { ServerlistModel } from '@db/Serverlist';
import { nowSeconds } from 'app/pubUtils/timeUtil';
import { checkWhiteList } from 'app/pubUtils/sysUtil';

module.exports = () => {
    return async function checkMainten(ctx, next) {
        const { serverId } = ctx.request.body;
        if (serverId) {
            let server = await ServerlistModel.findByServerId(serverId);
            if (server && server.maintenance && server.maintenance.isOpen && server.maintenance.startTime < nowSeconds() && server.maintenance.endTime > nowSeconds()) {
                let isWhiteList = await checkWhiteList(ctx.app.config.realEnv, ctx.clientIp, ctx.uid);
                if (isWhiteList) {
                    return await next();
                } else {
                    ctx.body = ctx.service.utils.resResult(STATUS.SERVER_MAINTENANCE);
                    return;
                }
            } else if(server && server.openTime > nowSeconds()) {
                let isWhiteList = await checkWhiteList(ctx.app.config.realEnv, ctx.clientIp, ctx.uid);
                if (isWhiteList) {
                    return await next();
                } else {
                    ctx.body = ctx.service.utils.resResult(STATUS.SERVER_IS_NOT_OPEN);
                    return;
                }
            }
        }
        return await next();
    };
};

