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 MarkPopupRead extends API {
    constructor() {
        super()
        this.setPath('/Popup/MarkRead')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        const { uuid, session, popup_id } = req.body
        if ([uuid, session, popup_id].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 popupRows = await db.query('SELECT id FROM site_popup WHERE id = ?', [popup_id])
        if (!popupRows || popupRows.length === 0) {
            return res.json({ ...BaseStdResponse.ERR, msg: '公告不存在' })
        }

        const sql = `
            INSERT INTO site_popup_read (popup_id, user_uuid, read_at)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE read_at = VALUES(read_at)
        `
        const now = Date.now()
        const rows = await db.query(sql, [popup_id, uuid, now])
        if (!rows) return res.json({ ...BaseStdResponse.DATABASE_ERR })

        return res.json({ ...BaseStdResponse.OK })
    }
}

module.exports.MarkPopupRead = MarkPopupRead
