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

class ApproveSendCountRequest extends API {
    constructor() {
        super()
        this.setPath("/Admin/Goods/SendCountRequest/Approve")
        this.setMethod("POST")
    }

    async onRequest(req, res) {
        let { uuid, session, id } = req.body
        id = Number(id)

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

        if (!Number.isInteger(id) || id <= 0)
            return res.json({ ...BaseStdResponse.ERR, msg: "参数错误" })

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

        if (!await AccessControl.canAccess(uuid, ['action.goods.reviewSendCount']))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const conn = await db.connect()
        try {
            await conn.beginTransaction()

            const [requestRows] = await conn.execute(
                `SELECT id, sender_uuid, receiver_user_id, count, status
                 FROM lepao_send_count_request
                 WHERE id = ?
                 FOR UPDATE`,
                [id]
            )

            if (!requestRows || requestRows.length !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "未找到赠送申请记录！" })
            }

            const request = requestRows[0]
            if (request.status !== "pending") {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "该申请已审核，请刷新后重试！" })
            }

            const [senderRows] = await conn.execute(
                "SELECT username FROM users WHERE uuid = ?",
                [request.sender_uuid]
            )
            const senderUsername = senderRows && senderRows[0] ? senderRows[0].username : "未知用户"

            const [receiverRows] = await conn.execute(
                "SELECT uuid, lepao_count FROM users WHERE id = ? FOR UPDATE",
                [request.receiver_user_id]
            )
            if (!receiverRows || receiverRows.length !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "接收用户不存在，审核通过失败！" })
            }
            const receiverUuid = receiverRows[0].uuid
            const beforeCount = Number(receiverRows[0].lepao_count || 0)

            const [incResult] = await conn.execute(
                "UPDATE users SET lepao_count = lepao_count + ? WHERE id = ?",
                [request.count, request.receiver_user_id]
            )
            if (!incResult || incResult.affectedRows !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "接收用户不存在，审核通过失败！" })
            }

            const [updateResult] = await conn.execute(
                `UPDATE lepao_send_count_request
                 SET status = 'approved', reviewer_uuid = ?, reviewed_at = NOW(), reject_reason = NULL
                 WHERE id = ?`,
                [uuid, id]
            )
            if (!updateResult || updateResult.affectedRows !== 1) {
                await conn.rollback()
                return res.json({ ...BaseStdResponse.ERR, msg: "更新审核状态失败，请稍后再试！" })
            }

            await insertLedgerRecord({
                executor: conn,
                userUuid: receiverUuid,
                delta: Number(request.count || 0),
                balanceBefore: beforeCount,
                balanceAfter: beforeCount + Number(request.count || 0),
                bizType: 'gift_receive',
                bizId: `send_request:${id}`,
                operatorUuid: uuid,
                remark: `${senderUsername}赠送${request.count}次`
            })

            await conn.commit()
            const requestId = request.id
            const reviewTime = new Date().getTime()

            // 非阻塞通知接收人，不影响审核结果
            Promise.resolve().then(async () => {
                try {
                    const infoSql = `
                        SELECT
                            ru.email AS receiver_email,
                            ru.username AS receiver_username,
                            su.username AS sender_username
                        FROM users ru
                        LEFT JOIN users su ON su.uuid = ?
                        WHERE ru.id = ?
                    `
                    const infoRows = await db.query(infoSql, [request.sender_uuid, request.receiver_user_id])
                    if (!infoRows || infoRows.length !== 1 || !infoRows[0].receiver_email) {
                        this.logger.warn(`[SendCountNotify][approve][requestId=${requestId}] 接收人邮箱为空或用户不存在，跳过通知`)
                        return
                    }

                    await EmailTemplate.sendCountRequestApproved(infoRows[0].receiver_email, {
                        requestId,
                        senderUsername: infoRows[0].sender_username || "未知用户",
                        count: request.count,
                        reviewTime
                    })
                } catch (mailErr) {
                    this.logger.error(`[SendCountNotify][approve][requestId=${requestId}] 接收人通知发送失败：${mailErr.message || "未知错误"}`)
                }
            })

            return res.json({ ...BaseStdResponse.OK, msg: "审核通过成功" })
        } catch (err) {
            try { await conn.rollback() } catch (_) { }
            this.logger.error(`审核通过赠送申请失败！${err.message || "未知错误"}`)
            return res.json({ ...BaseStdResponse.ERR, msg: "审核通过失败，请稍后再试！" })
        } finally {
            if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
                conn.release()
            }
        }
    }
}

module.exports.ApproveSendCountRequest = ApproveSendCountRequest
