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

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

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id,
            title,
            slug,
            cover,
            describe,
            content,
            type,
            state
        } = req.body;

        if ([uuid, session, title, cover, content, type].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 time = new Date().getTime();

        try {
            if (!id) {
                let baseSlug = slug ? String(slug).trim().toLowerCase() : slugify(title);
                if (!isValidSlug(baseSlug))
                    return res.json({ ...BaseStdResponse.ERR, msg: '文章标识格式无效（3-64位小写字母、数字、连字符）' });

                const finalSlug = await ensureUniqueSlug(db, baseSlug);
                const articleCover = (cover && String(cover).trim()) ? String(cover).trim().slice(0, 16) : '📄';

                const sql = 'INSERT INTO article (title, slug, cover, time, content, author, state, `describe`, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)';
                const r = await db.query(sql, [title, finalSlug, articleCover, time, content, uuid, state, describe, type]);

                if (r && r.affectedRows > 0) {
                    return res.json({ ...BaseStdResponse.OK, id: r.insertId, slug: finalSlug });
                }
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '发表文章失败！数据库错误' });
            }

            const existing = await db.query('SELECT slug FROM article WHERE id = ?', [id]);
            if (!existing || existing.length === 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '文章不存在' });

            const articleCover = (cover && String(cover).trim()) ? String(cover).trim().slice(0, 16) : '📄';
            const sql = 'UPDATE article SET title = ?, cover = ?, content = ?, state = ?, `describe` = ?, type = ? WHERE id = ?';
            const r = await db.query(sql, [title, articleCover, content, state, describe, type, id]);

            if (r && r.affectedRows > 0) {
                return res.json({ ...BaseStdResponse.OK, slug: existing[0].slug });
            }
            return res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '发表文章失败！数据库错误' });
        } catch (err) {
            this.logger.error(`发表文章失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: "发表文章失败！" });
        }
    }
}

module.exports.PostArticle = PostArticle;
