/**
 * src/routes/broadcast.js
 * 
 * Public endpoint (extension):
 *   GET /api/v1/broadcast
 * 
 * Admin endpoints (Painel):
 *   GET  /api/admin/broadcasts
 *   POST /api/admin/broadcasts
 */
const express = require('express');
const router = express.Router();
const db = require('../db');
const { requireAuth, requireSuperAdmin } = require('../middleware/auth');

// ── Public (Extension) ───────────────────────────────────────────────────────

/**
 * GET /api/v1/broadcast
 * Retorna a mensagem ativa mais recente para a extensão.
 */
router.get('/broadcast', async (req, res) => {
    try {
        const [rows] = await db.query(
            'SELECT id, message, type, created_at FROM app_broadcasts WHERE is_active = TRUE ORDER BY created_at DESC LIMIT 1'
        );
        if (rows.length === 0) {
            return res.json({ message: null });
        }
        const b = rows[0];
        res.json({ ...b, is_active: !!b.is_active });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

// ── Admin (Painel) ───────────────────────────────────────────────────────────

/**
 * GET /api/admin/broadcasts
 */
router.get('/broadcasts', requireAuth, requireSuperAdmin, async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM app_broadcasts ORDER BY created_at DESC LIMIT 50');
        const mapped = rows.map(r => ({ ...r, is_active: !!r.is_active }));
        res.json(mapped);
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

/**
 * POST /api/admin/broadcasts
 * Cria uma nova mensagem ou desativa as anteriores.
 */
router.post('/broadcasts', requireAuth, requireSuperAdmin, async (req, res) => {
    const { message, type, is_active } = req.body;
    if (!message) return res.status(400).json({ error: 'Mensagem é obrigatória' });

    try {
        // Se estiver ativando uma nova, podemos opcionalmente desativar as outras
        if (is_active !== false) {
            await db.execute('UPDATE app_broadcasts SET is_active = FALSE');
        }

        const [result] = await db.execute(
            'INSERT INTO app_broadcasts (message, type, is_active) VALUES (?, ?, ?)',
            [message, type || 'info', is_active ? 1 : 0]
        );

        res.json({ id: result.insertId, ok: true });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

/**
 * PATCH /api/admin/broadcasts/:id
 * Alternar status
 */
router.patch('/broadcasts/:id', requireAuth, requireSuperAdmin, async (req, res) => {
    const { is_active } = req.body;
    try {
        if (is_active) {
            await db.execute('UPDATE app_broadcasts SET is_active = 0');
        }
        await db.execute('UPDATE app_broadcasts SET is_active = ? WHERE id = ?', [is_active ? 1 : 0, req.params.id]);
        res.json({ ok: true });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

/**
 * DELETE /api/admin/broadcasts/:id
 */
router.delete('/broadcasts/:id', requireAuth, requireSuperAdmin, async (req, res) => {
    try {
        await db.execute('DELETE FROM app_broadcasts WHERE id = ?', [req.params.id]);
        res.json({ ok: true });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

module.exports = router;
