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

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

    async onRequest(req, res) {
        let { uuid, session, id } = req.query;

        if ([uuid, session, id].some(value => value === '' || value === null || value === 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 
                a.id,
                a.slug,
                a.title,
                a.cover,
                a.describe,
                a.content,
                a.type,
                a.state,
                a.views,
                a.time,
                u.username AS author
            FROM article a
            LEFT JOIN users u ON a.author = u.uuid
            WHERE a.id = ?
        `;

        try {
            const rows = await db.query(sql, [id]);

            if (!rows || rows.length !== 1)
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: '文章不存在' });

            res.json({
                ...BaseStdResponse.OK,
                data: rows[0]
            });
        } catch (err) {
            this.logger.error(`获取文章失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: '获取文章失败！' });
        }
    }
}

module.exports.GetArticle = GetArticle;
