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) {
        let { id } = req.query

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

        let sql = 'UPDATE article SET views = views + 1 WHERE state = 1 AND id = ?'
        await db.query(sql, [id])

        sql = `
                SELECT 
                    a.id,
                    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 = u.uuid
                WHERE 
                    a.state = 1 AND a.id = ?
            `

        let rows = await db.query(sql, [id])

        if (!rows || rows.length !== 1)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '文章不存在或无查看权限'
            })

        res.json({
            ...BaseStdResponse.OK,
            data: rows
        })
    }

}

module.exports.GetArticle = GetArticle;