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

class SendCount extends API {
    constructor() {
        super()
        this.setPath("/Goods/SendCount")
        this.setMethod("POST")
    }

    async onRequest(req, res) {
        let { uuid, session, username, count } = req.body
        username = typeof username === "string" ? username.trim() : username
        count = Number(count)

        if ([uuid, session, username, count].some(v => v == null || v === "" || Number.isNaN(count)))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })

        if (!Number.isInteger(count) || count < 1 || count > 9999)
            return res.json({ ...BaseStdResponse.ERR, msg: "超出赠送的次数范围，请重新选择赠送次数" })

        if (!(await AccessControl.checkSession(uuid, session)))
            return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })


        const conn = await db.connect() // 这里直接拿 connection
        try {
            await conn.beginTransaction()

            const [senderRows] = await conn.execute(
                "SELECT id, username, lepao_count FROM users WHERE uuid = ?",
                [uuid]
            )
            if (!senderRows || senderRows.length !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "获取用户信息失败！" })
            }

            const [targetRows] = await conn.execute(
                "SELECT id, uuid FROM users WHERE username = ?",
                [username]
            )
            if (!targetRows || targetRows.length !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "未找到接收用户，请检查用户名是否正确！" })
            }
            if (targetRows[0].uuid === uuid) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "不能给自己赠送次数！" })
            }

            const [decResult] = await conn.execute(
                "UPDATE users SET lepao_count = lepao_count - ? WHERE uuid = ? AND lepao_count >= ?",
                [count, uuid, count]
            )
            if (decResult.affectedRows !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "剩余乐跑次数不足，请购买后再赠送！" })
            }

            const [incResult] = await conn.execute(
                "UPDATE users SET lepao_count = lepao_count + ? WHERE id = ?",
                [count, targetRows[0].id]
            )
            if (incResult.affectedRows !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "赠送次数失败，请稍后再试！" })
            }

            await conn.commit()
            return res.json({ ...BaseStdResponse.OK, msg: "赠送成功" })

        } catch (err) {
            try { await conn.rollback() } catch (_) { }
            this.logger.error(`赠送乐跑次数失败！${err.message || "未知错误"}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: `赠送次数失败，请稍后再试！`
            })
        }
    }
}

module.exports.SendCount = SendCount
