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

// 公开/私密文章
class PublicArticle extends API {
    constructor() {
        super();

        this.setPath('/Admin/Article/Public');
        this.setMethod('POST');
    }

    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 permission = await AccessControl.getPermission(uuid);
        if (!permission.includes("admin") && !permission.includes("article")) {
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
            })
        }

        try {
            // 查询当前文章的状态
            let [currentState] = await db.query('SELECT state FROM article WHERE id = ?', [id]);

            if (!currentState) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    endpoint: 7894379,
                    msg: '文章不存在！'
                })
            }

            // 计算新的状态
            let newState = currentState.state === 0 ? 1 : 0;

            // 更新状态
            let sql = 'UPDATE article SET state = ? WHERE id = ?';
            let result = await db.query(sql, [newState, id]);

            if (result && result.affectedRows > 0) {
                return res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                return res.json({
                    ...BaseStdResponse.ERR,
                    endpoint: 7894378,
                    msg: '修改文章状态失败！数据库错误',
                });
            }
        } catch (err) {
            this.logger.error(`修改文章状态失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: "修改文章状态失败！",
            });
        }
    }
}

module.exports.PublicArticle = PublicArticle
