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

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

        this.setPath('/Admin/Order/Detail')
        this.setMethod('get')
    }

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

        if (!uuid || !session || !orderId) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })
        }

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

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

        const sql = `
            SELECT
                o.orderId,
                o.create_time,
                o.pay_time,
                o.price,
                o.original_price,
                o.discount_amount,
                o.coupon_code,
                o.state,
                o.pay_id,
                o.pay_type,
                o.goods_id,
                o.create_user,
                g.name,
                g.content,
                g.icon,
                g.isHot,
                g.description,
                g.category,
                g.features,
                g.lepao_count,
                g.ic_count,
                g.vip,
                u.username,
                u.avatar,
                u.email AS user_email
            FROM
                orders o
            LEFT JOIN
                goods g ON o.goods_id = g.id
            LEFT JOIN
                users u ON o.create_user = u.uuid
            WHERE
                o.orderId = ?
        `
        const rows = await db.query(sql, [orderId])

        if (!rows || rows.length !== 1) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '订单不存在'
            })
        }

        const order = rows[0]
        const userRows = await db.query(
            'SELECT lepao_count FROM users WHERE uuid = ? LIMIT 1',
            [order.create_user]
        )
        const userLepaoCount = userRows?.[0]?.lepao_count ?? 0
        const refundEligibility = evaluateRefundEligibility({
            state: order.state,
            payTime: order.pay_time,
            userLepaoCount,
            goodsLepaoCount: order.lepao_count,
            skipTimeLimit: true
        })
        order.canRefund = refundEligibility.canRefund
        order.refundDisabledReason = refundEligibility.reason
        order.user_lepao_count = Number(userLepaoCount || 0)

        res.json({
            ...BaseStdResponse.OK,
            data: order
        })
    }
}

module.exports.GetOrderDetail = GetOrderDetail
