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

class RefundOrder extends API {
    constructor() {
        super()
        this.setPath('/Order/RefundOrder')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        const { uuid, session, orderId } = req.body

        if ([uuid, session, orderId].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
            })
        }

        try {
            const rows = await db.query(
                'SELECT orderId FROM orders WHERE orderId = ? AND create_user = ? LIMIT 1',
                [orderId, uuid]
            )
            if (!rows || rows.length !== 1) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '订单不存在'
                })
            }

            const result = await executeOrderRefund({
                orderId,
                operatorUuid: uuid,
                skipTimeLimit: false,
                logger: this.logger
            })

            if (!result.ok) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: result.msg
                })
            }

            this.logger.info(`用户申请退款成功，订单号：${orderId}`)
            return res.json({
                ...BaseStdResponse.OK,
                msg: result.msg
            })
        } catch (error) {
            this.logger.error(`用户退款接口异常 ${orderId}: ${error.stack || error}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '退款失败，请稍后再试'
            })
        }
    }
}

module.exports.RefundOrder = RefundOrder
