const API = require("../../lib/API");
const { BaseStdResponse } = require("../../BaseStdResponse");
const db = require("../../plugin/DataBase/db");
const AccessControl = require("../../lib/AccessControl");

class SetPermission extends API {
    constructor() {
        super();

        this.setPath('/Admin/SetPermission');
        this.setMethod('POST');
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            userid,
            manage
        } = req.body;

        if ([uuid, session, userid, manage].some(value => value === '' || value === null || value === undefined)) {
            res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 151456
            });
            return;
        }

        //检查session
        if (!await AccessControl.checkSession(uuid, session)) {
            res.json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 485367
            });
            return;
        }

        //确认操作人权限
        let permission = await AccessControl.getPermission(uuid);
        if (!permission.includes("admin")) {
            res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                endpoint: 4815478,
            });
            return;
        }

        let sql = `UPDATE users SET manage = ? WHERE id = ?`;
        let result = await db.query(sql, [manage, userid]);

        if (!result || result.affectedRows !== 1) {
            res.json({
                ...BaseStdResponse.DATABASE_ERR,
                endpoint: 5135135
            });
            return;
        }

        res.json({
            ...BaseStdResponse.OK
        });
    }
}

module.exports.SetPermission = SetPermission;