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

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

    async onRequest(req, res) {
        const {
            uuid, session, id, title, description, download_url, version,
            icon, button_text, button_color, platform, extract_code,
            changelog_html, sort_order, is_active
        } = req.body;

        if ([uuid, session, title, download_url].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('service'))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED });

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

        try {
            if (id) {
                const r = await db.query(`
                    UPDATE download_item SET
                        title = ?, description = ?, download_url = ?, version = ?,
                        icon = ?, button_text = ?, button_color = ?, platform = ?,
                        extract_code = ?, changelog_html = ?, sort_order = ?,
                        is_active = ?, updated_at = ?
                    WHERE id = ?
                `, [
                    String(title).trim(),
                    description || '',
                    String(download_url).trim(),
                    version || '',
                    safeIcon,
                    button_text || '立即下载',
                    button_color || 'primary',
                    platform || '',
                    extract_code || '',
                    changelog_html || '',
                    sortOrder,
                    active,
                    now,
                    id
                ]);
                if (!r || r.affectedRows === 0)
                    return res.json({ ...BaseStdResponse.ERR, msg: '更新下载项失败' });
                return res.json({ ...BaseStdResponse.OK, id });
            }

            const r = await db.query(`
                INSERT INTO download_item
                    (title, description, download_url, version, icon, button_text,
                     button_color, platform, extract_code, changelog_html,
                     sort_order, is_active, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `, [
                String(title).trim(),
                description || '',
                String(download_url).trim(),
                version || '',
                safeIcon,
                button_text || '立即下载',
                button_color || 'primary',
                platform || '',
                extract_code || '',
                changelog_html || '',
                sortOrder,
                active,
                now,
                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.AdminDownloadUpsert = AdminDownloadUpsert;
