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

class ChangeLepaoCount extends API {
    constructor() {
        super()

        this.setPath('/Admin/User/ChangeLepaoCount')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            userid,
            lepao_count,
            remark
        } = req.body
        remark = typeof remark === 'string' ? remark.trim() : ''

        if ([uuid, session, userid, lepao_count].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })
        if (remark.length > 255)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '备注长度不能超过255个字符'
            })

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

        // 检查权限
        if (!await AccessControl.canAccess(uuid, ['action.user.changeCount']))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        const conn = await db.connect()
        try {
            await conn.beginTransaction()
            const [userRows] = await conn.execute(
                'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
                [userid]
            )
            if (!userRows || userRows.length !== 1) {
                await conn.rollback()
                return res.json({
                    ...BaseStdResponse.MISSING_FILE,
                    msg: '未找到用户信息'
                })
            }

            const beforeCount = Number(userRows[0].lepao_count || 0)
            const targetCount = Number(lepao_count)
            const delta = targetCount - beforeCount
            const [r] = await conn.execute(
                'UPDATE users SET lepao_count = ? WHERE uuid = ?',
                [targetCount, userid]
            )
            if (!r || r.affectedRows !== 1) {
                await conn.rollback()
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })
            }

            if (delta !== 0) {
                await insertLedgerRecord({
                    executor: conn,
                    userUuid: userid,
                    delta,
                    balanceBefore: beforeCount,
                    balanceAfter: targetCount,
                    bizType: 'admin_adjust',
                    bizId: `admin_adjust:${Date.now()}:${userid}`,
                    operatorUuid: uuid,
                    remark: remark || '系统调整里程'
                })
            }

            await conn.commit()
        } catch (error) {
            try { await conn.rollback() } catch (_) { }
            this.logger.error(`管理员调整里程失败: ${error.stack || error}`)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR
            })
        } finally {
            if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
                conn.release()
            }
        }

        res.json({
            ...BaseStdResponse.OK
        })

    }
}

module.exports.ChangeLepaoCount = ChangeLepaoCount