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

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

    async onRequest(req, res) {
        const { userid } = req.query

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

        const rows = await db.query(
            "SELECT uuid, username, permission FROM users WHERE uuid = ? LIMIT 1",
            [userid]
        )

        if (!rows || rows.length !== 1)
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到用户" })

        const directPermissionCodes = await AccessControl.getUserDirectPermissionCodes(userid)
        const deniedBasicPermissionCodes = await AccessControl.getUserDeniedBasicPermissionCodes(userid)
        const effectivePermissionCodes = await AccessControl.getUserPermissionCodes(userid)

        return res.json({
            ...BaseStdResponse.OK,
            data: {
                user: {
                    uuid: rows[0].uuid,
                    username: rows[0].username,
                    roles: AccessControl.parseArray(rows[0].permission)
                },
                directPermissionCodes,
                deniedBasicPermissionCodes,
                effectivePermissionCodes
            }
        })
    }
}

module.exports.GetUserPermissions = GetUserPermissions
