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

class ChangeLepaoCount extends API {
    constructor() {
        super()

        this.setPath('/Admin/User/ChangeLepaoCount')
        this.setMethod('POST')
    }

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

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

        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("service"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        let sql = 'UPDATE users SET lepao_count = ? WHERE uuid = ?'
        let r = await db.query(sql, [lepao_count, userid])
        if (!r || r.affectedRows !== 1)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR
            })

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

    }
}

module.exports.ChangeLepaoCount = ChangeLepaoCount