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

class SetSendCountAutoApprove extends API {
    constructor() {
        super()
        this.setPath("/Admin/User/SetSendCountAutoApprove")
        this.setMethod("POST")
    }

    async onRequest(req, res) {
        let { uuid, session, userid, send_count_auto_approve } = req.body
        const flag = Number(send_count_auto_approve)

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

        if (![0, 1].includes(flag))
            return res.json({ ...BaseStdResponse.ERR, msg: "参数错误" })

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

        if (!await AccessControl.canAccess(uuid, ['action.user.setSendCountAutoApprove']))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const conn = await db.connect()
        try {
            const [r] = await conn.execute(
                "UPDATE users SET send_count_auto_approve = ? WHERE uuid = ?",
                [flag, userid]
            )
            if (!r || r.affectedRows !== 1) {
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到用户或更新失败" })
            }
            return res.json({ ...BaseStdResponse.OK, msg: "已保存" })
        } catch (err) {
            this.logger.error(`设置赠送免审白名单失败: ${err.message || err}`)
            return res.json({ ...BaseStdResponse.ERR, msg: "保存失败，请稍后再试" })
        } finally {
            if (conn?.connection && typeof conn.connection.release === "function" && typeof conn?.release === "function") {
                conn.release()
            }
        }
    }
}

module.exports.SetSendCountAutoApprove = SetSendCountAutoApprove
