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

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

    async onRequest(req, res) {
        const { uuid, session, id, name, slug, icon, sort_order, is_active } = req.body;
        if ([uuid, session, name, slug].some(v => v === '' || v === null || v === 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 safeSlug = String(slug).trim().toLowerCase();
        if (!isValidSlug(safeSlug) || safeSlug.length > 32)
            return res.json({ ...BaseStdResponse.ERR, msg: '分类标识格式无效（3-32位小写字母、数字、连字符）' });

        const safeIcon = icon ? String(icon).trim().slice(0, 16) : null;
        const sortOrder = Number(sort_order) || 0;
        const active = Number(is_active) === 0 ? 0 : 1;
        const now = Date.now();

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

                const oldSlug = existing[0].slug;
                if (oldSlug !== safeSlug) {
                    const dup = await db.query('SELECT id FROM article_category WHERE slug = ? AND id != ?', [safeSlug, id]);
                    if (dup && dup.length > 0)
                        return res.json({ ...BaseStdResponse.ERR, msg: '分类标识已存在' });
                    await db.query('UPDATE article SET type = ? WHERE type = ?', [safeSlug, oldSlug]);
                }

                const r = await db.query(
                    'UPDATE article_category SET name = ?, slug = ?, icon = ?, sort_order = ?, is_active = ? WHERE id = ?',
                    [String(name).trim(), safeSlug, safeIcon, sortOrder, active, id]
                );
                if (!r || r.affectedRows === 0)
                    return res.json({ ...BaseStdResponse.ERR, msg: '更新分类失败' });
                return res.json({ ...BaseStdResponse.OK, id });
            }

            const dup = await db.query('SELECT id FROM article_category WHERE slug = ?', [safeSlug]);
            if (dup && dup.length > 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '分类标识已存在' });

            const r = await db.query(
                'INSERT INTO article_category (name, slug, icon, sort_order, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?)',
                [String(name).trim(), safeSlug, safeIcon, sortOrder, active, now]
            );
            if (!r || r.affectedRows === 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '创建分类失败' });
            return res.json({ ...BaseStdResponse.OK, id: r.insertId });
        } catch (err) {
            this.logger.error(`保存文章分类失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: '保存文章分类失败！' });
        }
    }
}

module.exports.AdminArticleCategoryUpsert = AdminArticleCategoryUpsert;
