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 GetUnreadPopup extends API {
    constructor() {
        super()
        this.setPath('/Popup/Unread')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        const { uuid, session, limit } = req.query
        if ([uuid, session].some(v => v === '' || v === null || v === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })

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

        const take = Number(limit) > 0 ? Number(limit) : 1
        const sql = `
            SELECT
                p.id,
                p.title,
                p.content_html,
                p.priority,
                p.repeat_show,
                p.start_at,
                p.end_at,
                p.created_at,
                p.updated_at
            FROM site_popup p
            LEFT JOIN site_popup_read r ON r.popup_id = p.id AND r.user_uuid COLLATE utf8mb4_general_ci = CONVERT(? USING utf8mb4) COLLATE utf8mb4_general_ci
            WHERE
                p.is_active = 1
                AND (p.repeat_show = 1 OR r.popup_id IS NULL)
                AND (p.start_at IS NULL OR p.start_at <= NOW())
                AND (p.end_at IS NULL OR p.end_at >= NOW())
            ORDER BY p.priority DESC, p.id DESC
            LIMIT ?
        `
        const rows = await db.query(sql, [uuid, String(take)])
        if (!rows) return res.json({ ...BaseStdResponse.DATABASE_ERR })

        return res.json({
            ...BaseStdResponse.OK,
            data: rows
        })
    }
}

module.exports.GetUnreadPopup = GetUnreadPopup
