/**
 * src/routes/prompts.js
 *
 * Public endpoint (extension):
 *   GET /api/v1/lovable/prompts
 *
 * Admin endpoints (Painel):
 *   GET    /api/admin/prompts
 *   POST   /api/admin/prompts
 *   PATCH  /api/admin/prompts/:id
 *   DELETE /api/admin/prompts/:id
 *
 * NOTE: This router is mounted at BOTH /api/v1/lovable AND /api/admin.
 * To avoid route shadowing, the public-only GET is on path /prompts/public
 * and server.js aliases /api/v1/lovable/prompts → /prompts/public.
 * The admin GET at /prompts requires requireAuth.
 */
const express = require('express');
const router = express.Router();
const db = require('../db');
const { requireAuth, requireSuperAdmin } = require('../middleware/auth');

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

/**
 * GET /api/v1/lovable/prompts
 * Retorna a biblioteca de prompts ativos (sem autenticação).
 * Rota separada em /prompts/public para evitar shadowing.
 */
router.get('/prompts/public', async (req, res) => {
    try {
        const [rows] = await db.query(
            'SELECT id, title, content, category FROM app_prompts WHERE is_active = 1 ORDER BY category, title'
        );
        res.json(rows);
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

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

/**
 * GET /api/admin/prompts
 * Aberto para qualquer autenticado (revendedores podem ver a biblioteca)
 */
router.get('/prompts', requireAuth, async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM app_prompts ORDER BY created_at DESC');
        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/prompts
 */
router.post('/prompts', requireAuth, requireSuperAdmin, async (req, res) => {
    const { title, content, category, is_active } = req.body;
    if (!title || !content) return res.status(400).json({ error: 'Título e conteúdo são obrigatórios' });

    try {
        const [result] = await db.execute(
            'INSERT INTO app_prompts (title, content, category, is_active) VALUES (?, ?, ?, ?)',
            [title, content, category || 'Geral', is_active ? 1 : 0]
        );
        res.json({ id: result.insertId, ok: true });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

/**
 * PATCH /api/admin/prompts/:id
 */
router.patch('/prompts/:id', requireAuth, requireSuperAdmin, async (req, res) => {
    const { title, content, category, is_active } = req.body;
    try {
        let query = 'UPDATE app_prompts SET ';
        const params = [];
        const updates = [];

        if (title !== undefined) { updates.push('title = ?'); params.push(title); }
        if (content !== undefined) { updates.push('content = ?'); params.push(content); }
        if (category !== undefined) { updates.push('category = ?'); params.push(category); }
        if (is_active !== undefined) {
            updates.push('is_active = ?');
            params.push(is_active ? 1 : 0);
        }

        if (updates.length === 0) return res.json({ ok: true });

        query += updates.join(', ') + ' WHERE id = ?';
        params.push(req.params.id);

        await db.execute(query, params);
        res.json({ ok: true });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

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

module.exports = router;
