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

class RefundOrder extends API {
    constructor() {
        super()
        this.setPath('/Admin/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
            })
        }

        const permission = await AccessControl.getPermission(uuid)
        if (!permission.includes('admin') && !permission.includes('product')) {
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })
        }

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

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

        this.logger.info(`管理员退款成功，订单号：${orderId}，操作人：${uuid}`)
        return res.json({
            ...BaseStdResponse.OK,
            msg: result.msg
        })
    }
}

module.exports.RefundOrder = RefundOrder
