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

class AdminPopupReadList extends API {
    constructor() {
        super()
        this.setPath('/Admin/Popup/ReadList')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        const { uuid, session, popup_id, keyword, pagesize, current } = req.query
        if ([uuid, session, popup_id, pagesize, current].some(v => v === '' || v === null || v === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        if (isNaN(pagesize) || Number(pagesize) <= 0 || isNaN(current) || Number(current) <= 0)
            return res.json({ ...BaseStdResponse.ERR, msg: '参数错误' })

        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("service") && !permission.includes("server"))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const offset = (Number(current) - 1) * Number(pagesize)
        const where = ['r.popup_id = ?']
        const params = [popup_id]
        const countParams = [popup_id]
        if (keyword) {
            where.push('(u.uuid COLLATE utf8mb4_general_ci LIKE CONVERT(? USING utf8mb4) COLLATE utf8mb4_general_ci OR u.username COLLATE utf8mb4_general_ci LIKE CONVERT(? USING utf8mb4) COLLATE utf8mb4_general_ci)')
            params.push(`%${keyword}%`, `%${keyword}%`)
            countParams.push(`%${keyword}%`, `%${keyword}%`)
        }

        const whereSql = where.join(' AND ')
        const listSql = `
            SELECT
                r.popup_id,
                r.user_uuid,
                r.read_at,
                u.username,
                u.avatar
            FROM site_popup_read r
            LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = r.user_uuid COLLATE utf8mb4_general_ci
            WHERE ${whereSql}
            ORDER BY r.read_at DESC
            LIMIT ? OFFSET ?
        `
        const countSql = `SELECT COUNT(*) AS total FROM site_popup_read r LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = r.user_uuid COLLATE utf8mb4_general_ci WHERE ${whereSql}`
        params.push(String(pagesize), String(offset))

        const rows = await db.query(listSql, params)
        const countRows = await db.query(countSql, countParams)
        if (!rows || !countRows) return res.json({ ...BaseStdResponse.DATABASE_ERR })

        return res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current: Number(current),
                pagesize: Number(pagesize),
                total: countRows[0]?.total || 0
            }
        })
    }
}

module.exports.AdminPopupReadList = AdminPopupReadList
