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 AdminNoticeUpsert extends API {
    constructor() {
        super()
        this.setPath('/Admin/Notice')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        const { uuid, session, key, content } = req.body
        if ([uuid, session, key, content].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 safeKey = String(key).trim()
        if (!safeKey) return res.json({ ...BaseStdResponse.ERR, msg: '公告标识不能为空' })

        const sql = `
            INSERT INTO notice (\`key\`, content)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE content = VALUES(content)
        `
        const rows = await db.query(sql, [safeKey, String(content)])
        if (!rows) return res.json({ ...BaseStdResponse.DATABASE_ERR })

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

module.exports.AdminNoticeUpsert = AdminNoticeUpsert
