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

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

        if ([uuid, session, title, content_html].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 cleanHtml = sanitizeHtml(content_html)
        const now = Date.now()
        const sql = `
            INSERT INTO site_popup
                (title, content_html, priority, is_active, repeat_show, start_at, end_at, created_by, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `
        const rows = await db.query(sql, [
            String(title).trim(),
            cleanHtml,
            Number(priority) || 0,
            Number(is_active) === 0 ? 0 : 1,
            Number(repeat_show) === 1 ? 1 : 0,
            normalizeDateTime(start_at),
            normalizeDateTime(end_at),
            uuid,
            now,
            now
        ])
        if (!rows || rows.affectedRows !== 1) return res.json({ ...BaseStdResponse.DATABASE_ERR })

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

module.exports.AdminCreatePopup = AdminCreatePopup
