const API = require('../../lib/API.js')
const db = require('../../plugin/DataBase/db.js')
const { BaseStdResponse } = require('../../BaseStdResponse.js')
const AccessControl = require('../../lib/AccessControl.js')
const { validateCoupon } = require('../../lib/CouponService.js')

class ValidateCoupon extends API {
    constructor() {
        super()
        this.setPath('/Coupon/Validate')
        this.setMethod('POST')
    }

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

        if ([uuid, session, code, goods_id].some((v) => v === '' || v == null)) {
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        }

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

        const goodsRows = await db.query(
            'SELECT id, price, state, num FROM goods WHERE id = ? LIMIT 1',
            [goods_id]
        )
        if (!goodsRows || goodsRows.length !== 1) {
            return res.json({ ...BaseStdResponse.ERR, msg: '商品不存在' })
        }
        const goods = goodsRows[0]
        if (goods.state !== 1 || goods.num < 1) {
            return res.json({ ...BaseStdResponse.ERR, msg: '商品不可购买' })
        }

        const result = await validateCoupon({
            code,
            userUuid: uuid,
            goodsId: goods_id,
            goodsPrice: goods.price
        })

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

        return res.json({
            ...BaseStdResponse.OK,
            data: {
                code: result.code,
                name: result.name,
                displayDiscount: result.displayDiscount,
                originalPrice: result.originalPrice,
                discountAmount: result.discountAmount,
                finalPrice: result.finalPrice
            }
        })
    }
}

module.exports.ValidateCoupon = ValidateCoupon
