const API = require('../../../lib/API.js')
const db = require('../../../plugin/DataBase/db.js')
const { BaseStdResponse } = require('../../../BaseStdResponse.js')
const AccessControl = require('../../../lib/AccessControl.js')
class CouponDetail extends API {
    constructor() {
        super()
        this.setPath('/Admin/Coupon/Detail')
        this.setMethod('GET')
    }

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

        if ([uuid, session, 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 permission = await AccessControl.getPermission(uuid)
        if (!permission.includes('admin') && !permission.includes('product')) {
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })
        }

        const rows = await db.query('SELECT * FROM coupons WHERE id = ? LIMIT 1', [id])
        if (!rows || rows.length !== 1) {
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: '优惠码不存在' })
        }

        const coupon = rows[0]
        const users = await db.query(
            `SELECT cu.user_uuid, u.username FROM coupon_users cu
             LEFT JOIN users u ON u.uuid = cu.user_uuid
             WHERE cu.coupon_id = ?`,
            [id]
        )
        const goods = await db.query(
            `SELECT cg.goods_id, g.name FROM coupon_goods cg
             LEFT JOIN goods g ON g.id = cg.goods_id
             WHERE cg.coupon_id = ?`,
            [id]
        )

        return res.json({
            ...BaseStdResponse.OK,
            data: {
                ...coupon,
                allowedUsers: (users || []).map((r) => ({
                    uuid: r.user_uuid,
                    username: r.username
                })),
                allowedGoods: (goods || []).map((r) => ({
                    id: r.goods_id,
                    name: r.name
                }))
            }
        })
    }
}

module.exports.CouponDetail = CouponDetail
