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

function normalizeDateTime(value) {
    if (value === undefined || value === null || value === '') return null
    const n = Number(value)
    if (!Number.isNaN(n) && Number.isFinite(n)) {
        const d = new Date(n)
        if (!Number.isNaN(d.getTime())) {
            return d.toISOString().slice(0, 19).replace('T', ' ')
        }
    }
    return String(value)
}

class AdminUpdatePopup extends API {
    constructor() {
        super()
        this.setPath('/Admin/Popup')
        this.setMethod('PUT')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id,
            title,
            content_html,
            priority,
            is_active,
            repeat_show,
            start_at,
            end_at
        } = req.body

        if ([uuid, session, 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 permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("server"))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const sets = ['updated_at = ?']
        const params = [Date.now()]
        if (title !== undefined) {
            sets.push('title = ?')
            params.push(String(title).trim())
        }
        if (content_html !== undefined) {
            sets.push('content_html = ?')
            params.push(sanitizeHtml(content_html))
        }
        if (priority !== undefined) {
            sets.push('priority = ?')
            params.push(Number(priority) || 0)
        }
        if (is_active !== undefined) {
            sets.push('is_active = ?')
            params.push(Number(is_active) === 0 ? 0 : 1)
        }
        if (repeat_show !== undefined) {
            sets.push('repeat_show = ?')
            params.push(Number(repeat_show) === 1 ? 1 : 0)
        }
        if (start_at !== undefined) {
            sets.push('start_at = ?')
            params.push(normalizeDateTime(start_at))
        }
        if (end_at !== undefined) {
            sets.push('end_at = ?')
            params.push(normalizeDateTime(end_at))
        }

        if (sets.length === 1) {
            return res.json({ ...BaseStdResponse.ERR, msg: '缺少更新字段' })
        }

        const sql = `UPDATE site_popup SET ${sets.join(', ')} WHERE id = ?`
        params.push(id)
        const rows = await db.query(sql, params)
        if (!rows) return res.json({ ...BaseStdResponse.DATABASE_ERR })
        if (rows.affectedRows !== 1) return res.json({ ...BaseStdResponse.ERR, msg: '公告不存在或未修改' })

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

module.exports.AdminUpdatePopup = AdminUpdatePopup
