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

class AdminArticleCategoryDelete extends API {
    constructor() {
        super();
        this.setPath('/Admin/Article/Category');
        this.setMethod('DELETE');
    }

    async onRequest(req, res) {
        const { uuid, session, id } = req.body;
        if ([uuid, session, id].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('article'))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED });

        try {
            const cat = await db.query('SELECT slug FROM article_category WHERE id = ?', [id]);
            if (!cat || cat.length === 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '分类不存在' });

            const count = await db.query('SELECT COUNT(*) AS total FROM article WHERE type = ?', [cat[0].slug]);
            if (count && count[0].total > 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '该分类下仍有文章，无法删除' });

            const r = await db.query('DELETE FROM article_category WHERE id = ?', [id]);
            if (!r || r.affectedRows === 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '删除分类失败' });
            return res.json({ ...BaseStdResponse.OK });
        } catch (err) {
            this.logger.error(`删除文章分类失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: '删除文章分类失败！' });
        }
    }
}

module.exports.AdminArticleCategoryDelete = AdminArticleCategoryDelete;
