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

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

    async onRequest(req, res) {
        const { slug } = req.query;

        if (!slug) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 153123
            });
        }

        const safeSlug = String(slug).trim();

        try {
            await db.query('UPDATE article SET views = views + 1 WHERE state = 1 AND slug = ?', [safeSlug]);

            const sql = `
                SELECT 
                    a.slug,
                    a.title,
                    a.cover,
                    a.\`describe\`,
                    a.content,
                    a.type,
                    a.views,
                    a.time,
                    u.username AS author
                FROM article a
                LEFT JOIN users u ON a.author COLLATE utf8mb4_general_ci = u.uuid COLLATE utf8mb4_general_ci
                WHERE a.state = 1 AND a.slug = ?
            `;

            const rows = await db.query(sql, [safeSlug]);

            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;
