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

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

    async onRequest(req, res) {
        const { userid, permissionCodes, deniedBasicPermissionCodes } = req.body

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

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

        if (deniedBasicPermissionCodes !== undefined && deniedBasicPermissionCodes !== null && !Array.isArray(deniedBasicPermissionCodes))
            return res.json({ ...BaseStdResponse.ERR, msg: "基础权限关闭列表格式错误" })

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

        try {
            await AccessControl.setUserPermissionCodes(userid, permissionCodes)
            if (Array.isArray(deniedBasicPermissionCodes))
                await AccessControl.setUserDeniedBasicPermissionCodes(userid, deniedBasicPermissionCodes)
            const effectivePermissionCodes = await AccessControl.getUserPermissionCodes(userid)
            return res.json({
                ...BaseStdResponse.OK,
                msg: "权限已保存",
                data: { effectivePermissionCodes }
            })
        } catch (error) {
            return res.json({ ...BaseStdResponse.ERR, msg: error.message || "保存权限失败" })
        }
    }
}

module.exports.SetUserPermissions = SetUserPermissions
