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 ListCoupons extends API {
    constructor() {
        super()
        this.setPath('/Admin/Coupon/List')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        const { uuid, session, pagesize, current, keyword, state } = req.query

        if ([uuid, session, pagesize, current].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 pageSize = Math.max(1, Number(pagesize))
        const page = Math.max(1, Number(current))
        const offset = (page - 1) * pageSize

        let sql = `SELECT * FROM coupons WHERE 1=1`
        let countSql = `SELECT COUNT(*) AS total FROM coupons WHERE 1=1`
        const params = []
        const countParams = []

        if (keyword) {
            sql += ` AND (code LIKE ? OR name LIKE ?)`
            countSql += ` AND (code LIKE ? OR name LIKE ?)`
            const kw = `%${keyword}%`
            params.push(kw, kw)
            countParams.push(kw, kw)
        }

        const stateNum = Number(state)
        if (
            state !== undefined &&
            state !== '' &&
            state !== '-1' &&
            !Number.isNaN(stateNum) &&
            stateNum !== -1
        ) {
            sql += ` AND state = ?`
            countSql += ` AND state = ?`
            params.push(stateNum)
            countParams.push(stateNum)
        }

        sql += ` ORDER BY id DESC LIMIT ? OFFSET ?`
        params.push(String(pageSize), String(offset))

        const rows = await db.query(sql, params)
        const countResult = await db.query(countSql, countParams)
        const total = Number(countResult?.[0]?.total || 0)

        return res.json({
            ...BaseStdResponse.OK,
            data: rows || [],
            pagination: {
                current: page,
                pagesize: pageSize,
                total,
                totalPages: Math.ceil(total / pageSize)
            }
        })
    }
}

module.exports.ListCoupons = ListCoupons
