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

class DeleteRule extends API {
    constructor() {
        super();

        this.setPath('/IC/Rule')
        this.setMethod('DELETE')
    }

    async onRequest(req, res) {
        let { uuid, session, id } = req.body

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

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

        let sql = 'DELETE FROM ic_rule WHERE id = ? AND create_user = ?'
        let r = await db.query(sql, [id, uuid])

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '删除规则失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`删除规则失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "删除规则失败！",
            });
        }
    }
}

module.exports.DeleteRule = DeleteRule