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

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

    async onRequest(req, res) {
        let { pagesize, current, type } = req.query;

        if ([pagesize, current, type].some(value => value === '' || value === null || value === undefined)) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            });
        }

        pagesize = parseInt(pagesize, 10);
        current = parseInt(current, 10);

        if (isNaN(pagesize) || pagesize <= 0 || isNaN(current) || current <= 0) {
            return res.json({ ...BaseStdResponse.ERR, msg: '参数错误' });
        }

        const offset = (current - 1) * pagesize;

        const sql = `
            SELECT 
                a.slug,
                a.title,
                a.\`describe\`,
                a.cover,
                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.type = ?
            ORDER BY a.id DESC
            LIMIT ? OFFSET ?
        `;

        const countSql = `
            SELECT COUNT(*) AS total
            FROM article a
            WHERE a.state = 1 AND a.type = ?
        `;

        try {
            const articles = await db.query(sql, [type, String(pagesize), String(offset)]);
            const countResult = await db.query(countSql, [type]);
            const total = countResult[0].total;
            const totalPages = Math.ceil(total / pagesize);

            res.json({
                ...BaseStdResponse.OK,
                data: articles || [],
                pagination: {
                    current,
                    pagesize,
                    total,
                    totalPages
                }
            });
        } catch (err) {
            this.logger.error(`获取文章列表失败！${err.stack}`);
            res.json({
                ...BaseStdResponse.ERR,
                msg: '获取文章列表失败！',
                endpoint: 153127
            });
        }
    }
}

module.exports.GetArticleList = GetArticleList;
