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

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

    async onRequest(req, res) {
        const { uuid, session, id } = req.body;
        if ([uuid, session, id].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 });

        try {
            const r = await db.query('DELETE FROM download_item WHERE id = ?', [id]);
            if (!r || r.affectedRows === 0)
                return res.json({ ...BaseStdResponse.ERR, msg: '删除下载项失败' });
            return res.json({ ...BaseStdResponse.OK });
        } catch (err) {
            this.logger.error(`删除下载项失败！${err.stack}`);
            res.json({ ...BaseStdResponse.ERR, msg: '删除下载项失败！' });
        }
    }
}

module.exports.AdminDownloadDelete = AdminDownloadDelete;
