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

    async onRequest(req, res) {
        const { uuid, session, keyword, pagesize, current } = req.query
        if ([uuid, session, 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 = ['1 = 1']
        const params = []
        const countParams = []
        if (keyword) {
            where.push('(`key` LIKE ? OR content LIKE ?)')
            params.push(`%${keyword}%`, `%${keyword}%`)
            countParams.push(`%${keyword}%`, `%${keyword}%`)
        }
        const whereSql = where.join(' AND ')

        const listSql = `
            SELECT \`key\`, content
            FROM notice
            WHERE ${whereSql}
            ORDER BY \`key\` ASC
            LIMIT ? OFFSET ?
        `
        const countSql = `SELECT COUNT(*) AS total FROM notice 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.AdminNoticeList = AdminNoticeList
