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

class AdminArticleCategoryList extends API {
    constructor() {
        super();
        this.setPath('/Admin/Article/Category/List');
        this.setMethod('GET');
    }

    async onRequest(req, res) {
        const { uuid, session } = req.query;
        if ([uuid, session].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 });

        const sql = `
            SELECT id, name, slug, icon, sort_order, is_active, created_at
            FROM article_category
            ORDER BY sort_order ASC, id ASC
        `;
        try {
            const rows = await db.query(sql);
            res.json({ ...BaseStdResponse.OK, data: rows || [] });
        } catch (err) {
            this.logger.error(`获取文章分类列表失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: '获取文章分类列表失败！' });
        }
    }
}

module.exports.AdminArticleCategoryList = AdminArticleCategoryList;
