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

class AdminNoticeDelete extends API {
    constructor() {
        super()
        this.setPath('/Admin/Notice')
        this.setMethod('DELETE')
    }

    async onRequest(req, res) {
        const { uuid, session, key } = req.body
        if ([uuid, session, key].some(v => v === '' || v === null || v === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })

        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
        const permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("service") && !permission.includes("server"))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const rows = await db.query('DELETE FROM notice WHERE `key` = ?', [String(key)])
        if (!rows) return res.json({ ...BaseStdResponse.DATABASE_ERR })
        if (rows.affectedRows !== 1) return res.json({ ...BaseStdResponse.ERR, msg: '公告不存在' })

        return res.json({ ...BaseStdResponse.OK })
    }
}

module.exports.AdminNoticeDelete = AdminNoticeDelete
