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

class UpdateResourceRule extends API {
    constructor() {
        super()
        this.setPath("/Admin/Permission/Resource")
        this.setMethod("POST")
        this.setPermissionCode("action.user.permissionManage")
    }

    async onRequest(req, res) {
        const { id, required_codes, enabled } = req.body

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

        if (!Array.isArray(required_codes))
            return res.json({ ...BaseStdResponse.ERR, msg: "权限列表格式错误" })

        try {
            const ok = await AccessControl.updateResourceRule({ id, required_codes, enabled })
            if (!ok)
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到权限规则" })

            return res.json({ ...BaseStdResponse.OK, msg: "权限规则已保存" })
        } catch (error) {
            return res.json({ ...BaseStdResponse.ERR, msg: error.message || "保存权限规则失败" })
        }
    }
}

module.exports.UpdateResourceRule = UpdateResourceRule
