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

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

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

        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.ban']))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        if (userid === uuid)
            return res.json({ ...BaseStdResponse.ERR, msg: "不能封禁自己的账号" })

        const targetRows = await db.query(
            "SELECT permission FROM users WHERE uuid = ? LIMIT 1",
            [userid]
        )
        if (!targetRows || targetRows.length === 0)
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到用户" })

        const targetPermission = targetRows[0].permission || []
        if (targetPermission.includes("admin") || targetPermission.includes("service"))
            return res.json({ ...BaseStdResponse.ERR, msg: "不能封禁管理员或客服账号" })

        const conn = await db.connect()
        try {
            const [r] = await conn.execute(
                "UPDATE users SET is_banned = ? WHERE uuid = ?",
                [flag, userid]
            )
            if (!r || r.affectedRows !== 1)
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到用户或更新失败" })

            if (flag === 1)
                await AccessControl.invalidateSession(userid)

            return res.json({
                ...BaseStdResponse.OK,
                msg: flag === 1 ? "已封禁该用户" : "已解除封禁"
            })
        } 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.SetUserBan = SetUserBan
