
/**
 * admin.js — Endpoints multi-tenant de gerenciamento de licenças
 */
const express = require('express');
const router = express.Router();
const db = require('../db');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const { requireAuth, requireSuperAdmin } = require('../middleware/auth');

/** GET /api/admin/stats — KPIs do dashboard */
router.get('/stats', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        let totalLicenses, activeLicenses, lovableAccounts, lovableProjects;

        if (isSuperAdmin) {
            [[{ total_licenses: totalLicenses }]] = await db.execute('SELECT COUNT(*) as total_licenses FROM licenses');
            [[{ active_licenses: activeLicenses }]] = await db.execute("SELECT COUNT(*) as active_licenses FROM licenses WHERE status = 'active'");
            [[{ lovable_accounts: lovableAccounts }]] = await db.execute('SELECT COUNT(*) as lovable_accounts FROM lovable_accounts');
            [[{ lovable_projects: lovableProjects }]] = await db.execute('SELECT COUNT(*) as lovable_projects FROM lovable_projects');
        } else {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            const placeholders = ownerIds.map(() => '?').join(',');

            [[{ total_licenses: totalLicenses }]] = await db.execute(`SELECT COUNT(*) as total_licenses FROM licenses WHERE owner_id IN (${placeholders})`, ownerIds);
            [[{ active_licenses: activeLicenses }]] = await db.execute(`SELECT COUNT(*) as active_licenses FROM licenses WHERE status = 'active' AND owner_id IN (${placeholders})`, ownerIds);

            [[{ lovable_accounts: lovableAccounts }]] = await db.execute(`
                SELECT COUNT(DISTINCT la.id) as lovable_accounts 
                FROM lovable_accounts la 
                JOIN licenses l ON la.license_key = l.license_key 
                WHERE l.owner_id IN (${placeholders})
            `, ownerIds);

            [[{ lovable_projects: lovableProjects }]] = await db.execute(`
                SELECT COUNT(DISTINCT p.id) as lovable_projects 
                FROM lovable_projects p 
                JOIN lovable_accounts la ON p.lovable_user_id = la.lovable_user_id
                JOIN licenses l ON la.license_key = l.license_key 
                WHERE l.owner_id IN (${placeholders})
            `, ownerIds);
        }

        res.json({ total_licenses: totalLicenses, active_licenses: activeLicenses, lovable_accounts: lovableAccounts, lovable_projects: lovableProjects });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** GET /api/admin/lovable/accounts */
router.get('/lovable/accounts', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        let query = `
            SELECT la.id, la.license_key, la.lovable_user_id, la.lovable_email, la.lovable_name, la.lovable_avatar,
                   la.workspace_id, la.workspace_name, la.workspace_plan,
                   la.credits_daily_used, la.credits_daily_limit, la.feature_flags, la.last_sync_at
            FROM lovable_accounts la
        `;

        let params = [];
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            query += ` JOIN licenses l ON la.license_key = l.license_key WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            params = ownerIds;
        }

        query += " ORDER BY la.last_sync_at DESC";

        const [accounts] = await db.execute(query, params);
        res.json({ accounts });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** GET /api/admin/lovable/accounts/:id/projects */
router.get('/lovable/accounts/:id/projects', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        let queryAcc = 'SELECT la.lovable_user_id FROM lovable_accounts la';
        let paramsAcc = [req.params.id];

        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryAcc += ` JOIN licenses l ON la.license_key = l.license_key WHERE la.id = ? AND l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            paramsAcc.push(...ownerIds);
        } else {
            queryAcc += ' WHERE la.id = ?';
        }

        const [accountRows] = await db.execute(queryAcc, paramsAcc);
        if (!accountRows[0]) return res.status(404).json({ error: 'Conta não encontrada ou sem permissão' });

        const [projects] = await db.execute(`
            SELECT project_id, project_name, project_url, screenshot_url,
                   status, edit_count, message_count, credit_total, is_starred, is_published, synced_at
            FROM lovable_projects
            WHERE lovable_user_id = ?
            ORDER BY synced_at DESC
        `, [accountRows[0].lovable_user_id]);
        res.json({ projects });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** GET /api/admin/credit-history — Histórico agregado de créditos Lovable por dia */
router.get('/credit-history', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;
        const days = Math.min(parseInt(req.query.days) || 30, 90);

        let queryHist = `
            SELECT
                DATE(h.recorded_at) as day,
                SUM(h.credits_daily_used) as total_used,
                MAX(h.credits_daily_limit) as avg_limit,
                COUNT(DISTINCT h.lovable_user_id) as unique_users
            FROM lovable_credit_history h
        `;
        let paramsHist = [];

        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryHist += ` JOIN licenses l ON h.license_key = l.license_key WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')}) AND h.recorded_at >= NOW() - INTERVAL ? DAY `;
            paramsHist.push(...ownerIds, days);
        } else {
            queryHist += " WHERE h.recorded_at >= NOW() - INTERVAL ? DAY ";
            paramsHist.push(days);
        }
        queryHist += " GROUP BY DATE(h.recorded_at) ORDER BY day ASC";

        const [history] = await db.execute(queryHist, paramsHist);

        // Feature flags mais comuns
        let queryFlags = 'SELECT feature_flags FROM lovable_accounts la';
        let paramsFlags = [];
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryFlags += ` JOIN licenses l ON la.license_key = l.license_key WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            paramsFlags = ownerIds;
        }
        const [accounts] = await db.execute(queryFlags, paramsFlags);

        const flagCounts = {};
        for (const row of accounts) {
            try {
                if (!row.feature_flags) continue;
                const flags = JSON.parse(row.feature_flags);
                for (const [k, v] of Object.entries(flags)) {
                    if (v) flagCounts[k] = (flagCounts[k] || 0) + 1;
                }
            } catch { }
        }
        const topFlags = Object.entries(flagCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 10)
            .map(([name, count]) => ({ name, count }));

        res.json({ history, top_flags: topFlags, total_accounts: accounts.length });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

function generateLicenseKey() {
    const seg = () => crypto.randomBytes(2).toString('hex').toUpperCase();
    return `ILVD-${seg()}-${seg()}-${seg()}`;
}

// Helper: Busca todos os IDs de descendentes na hierarquia (recursivo)
async function getDescendantIds(userId) {
    const [users] = await db.execute('SELECT id, parent_id FROM users');
    const descendants = [];

    function findChildren(parentId) {
        const children = users.filter(u => u.parent_id === parentId);
        for (const child of children) {
            descendants.push(child.id);
            findChildren(child.id);
        }
    }

    findChildren(userId);
    return descendants;
}

// ── USERS ──────────────────────────────────────────────────────

/** GET /api/admin/users — Lista usuários (Superadmin vê tudo, revendedor vê sua sub-hierarquia) */
router.get('/users', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        let query = `
            SELECT id, username, role, credits, parent_id, is_active, created_at,
                   (SELECT COUNT(*) FROM licenses WHERE owner_id = users.id) as license_count
            FROM users
        `;
        let params = [];

        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const targetIds = [userId, ...descendantIds];
            query += ` WHERE id IN (${targetIds.map(() => '?').join(',')})`;
            params = targetIds;
        }

        query += ' ORDER BY created_at DESC';

        const [users] = await db.execute(query, params);
        res.json({ users });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** POST /api/admin/users — cria novo revendedor */
router.post('/users', requireAuth, async (req, res) => {
    const { username, password, role = 'revendedor' } = req.body;
    if (!username || !password) {
        return res.status(400).json({ error: 'username e password são obrigatórios' });
    }
    if (password.length < 6) {
        return res.status(400).json({ error: 'Senha deve ter ao menos 6 caracteres' });
    }

    const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
    // Se não for superadmin, só pode criar 'revendedor' e o parent_id é obrigatório
    const targetRole = isSuperAdmin ? role : 'revendedor';
    const parentId = isSuperAdmin ? null : req.user.id;

    try {
        const hash = bcrypt.hashSync(password, 10);
        await db.execute('INSERT INTO users (username, password_hash, role, credits, parent_id) VALUES (?, ?, ?, 0, ?)', [username.trim(), hash, targetRole, parentId]);

        const [rows] = await db.execute('SELECT id, username, role, credits, parent_id, created_at FROM users WHERE username = ?', [username.trim()]);
        const newUser = rows[0];

        await db.addLog(req.user.id, 'USER_CREATE', `Criou novo revendedor: ${newUser.username} (${newUser.role})`, newUser.id, req.ip);

        res.status(201).json({ message: '✅ Revendedor criado', user: newUser });
    } catch (err) {
        if (err.message.includes('Duplicate entry')) {
            return res.status(409).json({ error: 'Nome de usuário já existe' });
        }
        res.status(500).json({ error: err.message });
    }
});

/** DELETE /api/admin/users/:id */
router.delete('/users/:id', requireAuth, async (req, res) => {
    const id = parseInt(req.params.id);
    const userId = req.user.id;
    const isPowerUser = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());

    if (!isPowerUser) {
        return res.status(403).json({ error: 'Apenas Administradores podem excluir revendedores' });
    }

    if (id === userId) {
        return res.status(400).json({ error: 'Você não pode deletar sua própria conta' });
    }

    try {
        const [uRows] = await db.execute('SELECT username FROM users WHERE id = ?', [id]);
        const targetUsername = uRows[0]?.username || id;

        // Antes de deletar, transfere todas as licenças do revendedor para quem está deletando
        await db.execute('UPDATE licenses SET owner_id = ? WHERE owner_id = ?', [userId, id]);

        const [result] = await db.execute('DELETE FROM users WHERE id = ?', [id]);
        if (result.affectedRows === 0) return res.status(404).json({ error: 'Usuário não encontrado' });

        await db.addLog(req.user.id, 'USER_DELETE', `Removeu revendedor: ${targetUsername}. Licenças transferidas para o administrador.`, id, req.ip);

        res.json({ message: '✅ Revendedor removido e licenças transferidas com sucesso' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** PATCH /api/admin/users/:id — atualiza dados (usuário/senha) */
router.patch('/users/:id', requireAuth, async (req, res) => {
    const id = parseInt(req.params.id);
    const userId = req.user.id;
    const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
    const { username, password, is_active } = req.body;

    try {
        // Verificar permissão: superadmin ou descendente
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            if (!descendantIds.includes(id)) {
                return res.status(403).json({ error: 'Sem permissão para editar este usuário' });
            }
        }

        const [uRows] = await db.execute('SELECT id, username FROM users WHERE id = ?', [id]);
        const targetUser = uRows[0];
        if (!targetUser) return res.status(404).json({ error: 'Usuário não encontrado' });

        let sql = 'UPDATE users SET ';
        const params = [];
        const updates = [];

        if (username && username.trim()) {
            updates.push('username = ?');
            params.push(username.trim());
        }

        if (password && password.length >= 6) {
            const hash = bcrypt.hashSync(password, 10);
            updates.push('password_hash = ?');
            params.push(hash);
        }

        if (is_active !== undefined) {
            updates.push('is_active = ?');
            params.push(is_active);
        }

        if (updates.length === 0) {
            return res.status(400).json({ error: 'Nada para atualizar' });
        }

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

        await db.execute(sql, params);

        let logMsg = `Atualizou dados do usuário ${targetUser.username}`;
        if (username) logMsg += ` (Nome mudou para ${username})`;
        if (is_active !== undefined) logMsg += ` (Status mudou para ${is_active ? 'ATIVO' : 'INATIVO'})`;

        await db.addLog(req.user.id, 'USER_UPDATE', logMsg, id, req.ip);

        res.json({ message: '✅ Dados atualizados com sucesso' });
    } catch (err) {
        if (err.message.includes('Duplicate entry')) {
            return res.status(409).json({ error: 'Nome de usuário já existe' });
        }
        res.status(500).json({ error: err.message });
    }
});

/** PATCH /api/admin/users/:id/credits — adiciona ou remove créditos */
router.patch('/users/:id/credits', requireAuth, async (req, res) => {
    const { amount } = req.body;
    const id = parseInt(req.params.id);
    const userId = req.user.id;
    const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());

    if (amount === undefined || isNaN(amount)) {
        return res.status(400).json({ error: 'amount é obrigatório (número inteiro)' });
    }

    try {
        // Superadmin transfere do nada; Revendedor transfere do seu próprio saldo
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            if (!descendantIds.includes(id)) {
                return res.status(403).json({ error: 'Sem permissão para ajustar créditos deste usuário' });
            }

            const transAmount = parseInt(amount);
            if (transAmount > 0) {
                // Adicionando créditos ao filho: Checa saldo do revendedor pai
                const [pRows] = await db.execute('SELECT credits FROM users WHERE id = ?', [userId]);
                if (pRows[0].credits < transAmount) {
                    return res.status(403).json({ error: 'Saldo insuficiente para transferir créditos' });
                }
                // Deduz do pai
                await db.execute('UPDATE users SET credits = credits - ? WHERE id = ?', [transAmount, userId]);
            } else if (transAmount < 0) {
                // Tirando créditos do filho: Devolve ao pai (limita ao que o filho tem)
                const [cRows] = await db.execute('SELECT credits FROM users WHERE id = ?', [id]);
                const actualRemoval = Math.min(cRows[0].credits, Math.abs(transAmount));
                if (actualRemoval > 0) {
                    await db.execute('UPDATE users SET credits = credits + ? WHERE id = ?', [actualRemoval, userId]);
                }
            }
        }

        const [rows] = await db.execute('SELECT id, username, credits FROM users WHERE id = ?', [id]);
        const user = rows[0];
        if (!user) return res.status(404).json({ error: 'Usuário não encontrado' });

        const newCredits = Math.max(0, user.credits + parseInt(amount));
        await db.execute('UPDATE users SET credits = ? WHERE id = ?', [newCredits, user.id]);

        await db.addLog(req.user.id, 'CREDIT_ADJUST', `Ajustou créditos de ${user.username}: ${user.credits} → ${newCredits}`, user.id, req.ip);

        res.json({
            message: `✅ Créditos atualizados: ${user.credits} → ${newCredits}`,
            username: user.username,
            credits_before: user.credits,
            credits_after: newCredits
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// ── LICENSES ───────────────────────────────────────────────────

/** GET /api/admin/licenses */
router.get('/licenses', requireAuth, async (req, res) => {
    try {
        let licenses;
        if (['superadmin', 'admin'].includes(req.user.role?.toLowerCase())) {
            const [rows] = await db.execute(`
                SELECT l.*, u.username as owner_name
                FROM licenses l
                LEFT JOIN users u ON l.owner_id = u.id
                ORDER BY l.created_at DESC
            `);
            licenses = rows;
        } else {
            const descendantIds = await getDescendantIds(req.user.id);
            const ownerIds = [req.user.id, ...descendantIds];
            const [rows] = await db.execute(`
                SELECT l.*, u.username as owner_name
                FROM licenses l
                LEFT JOIN users u ON l.owner_id = u.id
                WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')})
                ORDER BY l.created_at DESC
            `, ownerIds);
            licenses = rows;
        }
        res.json({ total: licenses.length, licenses });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** GET /api/admin/my-credits — revendedor consulta seus próprios créditos */
router.get('/my-credits', requireAuth, async (req, res) => {
    try {
        const [rows] = await db.execute('SELECT credits FROM users WHERE id = ?', [req.user.id]);
        const user = rows[0];
        res.json({ credits: user ? user.credits : 0 });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** POST /api/admin/licenses — consome créditos baseados na duração (1 crédito por 30 dias) */
router.post('/licenses', requireAuth, async (req, res) => {
    const {
        plan_name = 'Mensal',
        duration_minutes = 43200,
        notes = '',
        custom_key = null,
        custom_duration_days = null
    } = req.body;

    let minutes = parseInt(duration_minutes);
    let days = minutes / 1440;

    // Se informou dias customizados (ex: migração), sobrescreve os minutos
    if (custom_duration_days !== null && !isNaN(custom_duration_days)) {
        days = parseFloat(custom_duration_days);
        minutes = Math.round(days * 1440);
    }

    if (!minutes || minutes < 1) {
        return res.status(400).json({ error: 'Duração inválida' });
    }

    // Calcula créditos necessários (1 crédito a cada 43800 minutos / ~30.4 dias)
    let creditsNeeded = Math.ceil(minutes / 43800);
    if (plan_name === 'Demo' || minutes <= 60) creditsNeeded = 0;

    try {
        // Verifica e consome créditos (superadmin é isento)
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        if (!isSuperAdmin && creditsNeeded > 0) {
            const [rows] = await db.execute('SELECT credits FROM users WHERE id = ?', [req.user.id]);
            const user = rows[0];
            if (!user || user.credits < creditsNeeded) {
                return res.status(403).json({
                    error: `Créditos insuficientes. Esta licença requer ${creditsNeeded} créditos, mas você possui apenas ${user ? user.credits : 0}.`,
                    credits: user ? user.credits : 0
                });
            }
            await db.execute('UPDATE users SET credits = credits - ? WHERE id = ? AND credits >= ?', [creditsNeeded, req.user.id, creditsNeeded]);
        }

        let license_key = (['superadmin', 'admin'].includes(req.user.role?.toLowerCase()) && custom_key)
            ? custom_key.trim().toUpperCase()
            : generateLicenseKey();

        // Se for chave customizada, verificar se já existe
        if (custom_key && ['superadmin', 'admin'].includes(req.user.role?.toLowerCase())) {
            const [existing] = await db.execute('SELECT id FROM licenses WHERE license_key = ?', [license_key]);
            if (existing.length > 0) {
                return res.status(409).json({ error: 'Esta chave de licença já existe no sistema.' });
            }
        }

        await db.execute(`
            INSERT INTO licenses (license_key, plan_name, duration_days, duration_minutes, notes, status, owner_id)
            VALUES (?, ?, ?, ?, ?, 'active', ?)
        `, [license_key, plan_name, days, minutes, notes, req.user.id]);

        const [lRows] = await db.execute('SELECT * FROM licenses WHERE license_key = ?', [license_key]);
        const license = lRows[0];

        // Retorna créditos restantes para exibir no painel
        const [uRows] = await db.execute('SELECT credits FROM users WHERE id = ?', [req.user.id]);
        const updatedUser = uRows[0];

        await db.addLog(req.user.id, 'LICENSE_CREATE', `Gerou licença ${plan_name} (${minutes} min): ${license_key}`, license_key, req.ip);

        res.status(201).json({
            message: `✅ Licença de ${minutes} minutos criada! (${creditsNeeded} créditos consumidos)`,
            license,
            credits_remaining: ['superadmin', 'admin'].includes(req.user.role?.toLowerCase()) ? '∞' : (updatedUser ? updatedUser.credits : 0)
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// Helper: verifica se o usuário pode acessar a licença (ele mesmo ou seus descendentes)
async function canAccess(req, key) {
    try {
        const [rows] = await db.execute('SELECT owner_id FROM licenses WHERE license_key = ?', [key]);
        const license = rows[0];
        if (!license) return false;
        if (['superadmin', 'admin'].includes(req.user.role?.toLowerCase())) return true;

        if (license.owner_id === req.user.id) return true;

        // Verifica se o dono da licença é descendente do usuário logado
        const descendantIds = await getDescendantIds(req.user.id);
        return descendantIds.includes(license.owner_id);
    } catch (err) {
        return false;
    }
}

/** PATCH /api/admin/licenses/:key/revoke */
router.patch('/licenses/:key/revoke', requireAuth, async (req, res) => {
    const key = req.params.key.toUpperCase();
    if (!(await canAccess(req, key))) return res.status(403).json({ error: 'Sem permissão' });
    try {
        await db.execute("UPDATE licenses SET status = 'revoked' WHERE license_key = ?", [key]);
        await db.addLog(req.user.id, 'LICENSE_REVOKE', `Revogou licença: ${key}`, key, req.ip);
        res.json({ message: '✅ Licença revogada', license_key: key });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** PATCH /api/admin/licenses/:key/activate */
router.patch('/licenses/:key/activate', requireAuth, async (req, res) => {
    const key = req.params.key.toUpperCase();
    if (!(await canAccess(req, key))) return res.status(403).json({ error: 'Sem permissão' });
    try {
        const [rows] = await db.execute('SELECT expires_at, duration_minutes FROM licenses WHERE license_key = ?', [key]);
        const license = rows[0];

        if (!license) return res.status(404).json({ error: 'Licença não encontrada' });

        if (!license.expires_at) {
            // Se a licença ainda não tinha sido iniciada, calcula a expiração a partir do momento da ativação manual
            const expiresAt = new Date(Date.now() + license.duration_minutes * 60 * 1000);
            await db.execute(`
                UPDATE licenses 
                SET status = 'active', expires_at = ?, activated_at = CURRENT_TIMESTAMP 
                WHERE license_key = ?
            `, [expiresAt.toISOString().slice(0, 19).replace('T', ' '), key]);
        } else {
            // Se já tinha expiração (estava só revogada), apenas reativa
            await db.execute("UPDATE licenses SET status = 'active' WHERE license_key = ?", [key]);
        }

        await db.addLog(req.user.id, 'LICENSE_ACTIVATE', `Ativou/Reativou licença: ${key}`, key, req.ip);
        res.json({ message: '✅ Licença ativada', license_key: key });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** PATCH /api/admin/licenses/:key/reset-binding */
router.patch('/licenses/:key/reset-binding', requireAuth, async (req, res) => {
    const key = req.params.key.toUpperCase();
    if (!(await canAccess(req, key))) return res.status(403).json({ error: 'Sem permissão' });
    try {
        const [rows] = await db.execute('SELECT bound_user FROM licenses WHERE license_key = ?', [key]);
        const license = rows[0];
        if (!license) return res.status(404).json({ error: 'Licença não encontrada' });

        await db.execute('UPDATE licenses SET bound_user = NULL, bound_at = NULL WHERE license_key = ?', [key]);
        await db.addLog(req.user.id, 'LICENSE_RESET_BINDING', `Resetou vínculo da licença: ${key} (era ${license.bound_user})`, key, req.ip);

        res.json({ message: '✅ Vínculo resetado com sucesso' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** PATCH /api/admin/licenses/:key/renew */
router.patch('/licenses/:key/renew', requireAuth, async (req, res) => {
    const key = req.params.key.toUpperCase();
    const { duration_minutes = 43200 } = req.body;
    if (!(await canAccess(req, key))) return res.status(403).json({ error: 'Sem permissão' });

    const minutes = parseInt(duration_minutes);
    if (!minutes || minutes < 1) return res.status(400).json({ error: 'Duração inválida' });

    let creditsNeeded = Math.ceil(minutes / 43800);

    try {
        const [lRows] = await db.execute('SELECT expires_at, status FROM licenses WHERE license_key = ?', [key]);
        const license = lRows[0];
        if (!license) return res.status(404).json({ error: 'Licença não encontrada' });

        // Verifica crédito se não for superadmin
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        if (!isSuperAdmin && creditsNeeded > 0) {
            const [uRows] = await db.execute('SELECT credits FROM users WHERE id = ?', [req.user.id]);
            const user = uRows[0];
            if (!user || user.credits < creditsNeeded) {
                return res.status(403).json({ error: `Créditos insuficientes (${creditsNeeded} necessários)` });
            }
            await db.execute('UPDATE users SET credits = credits - ? WHERE id = ?', [creditsNeeded, req.user.id]);
        }

        let newExpiresAt;
        const now = new Date();
        const currentExpires = license.expires_at ? new Date(license.expires_at) : null;

        if (currentExpires && currentExpires > now) {
            // Extende a partir da expiração atual
            newExpiresAt = new Date(currentExpires.getTime() + minutes * 60 * 1000);
        } else {
            // Extende a partir de agora
            newExpiresAt = new Date(now.getTime() + minutes * 60 * 1000);
        }

        const mysqlExpiresAt = newExpiresAt.toISOString().slice(0, 19).replace('T', ' ');

        await db.execute(`
            UPDATE licenses 
            SET expires_at = ?, status = 'active', duration_minutes = duration_minutes + ?
            WHERE license_key = ?
        `, [mysqlExpiresAt, minutes, key]);

        await db.addLog(req.user.id, 'LICENSE_RENEW', `Renovou licença ${key} por +${minutes} min. Nova expiração: ${mysqlExpiresAt}`, key, req.ip);

        res.json({
            message: '✅ Licença renovada com sucesso',
            expires_at: mysqlExpiresAt,
            credits_consumed: creditsNeeded
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** DELETE /api/admin/licenses/:key/unbind — Só superadmin pode desvincular */
router.delete('/licenses/:key/unbind', requireAuth, requireSuperAdmin, async (req, res) => {
    const key = req.params.key.toUpperCase();
    try {
        const [rows] = await db.execute('SELECT license_key FROM licenses WHERE license_key = ?', [key]);
        const license = rows[0];
        if (!license) return res.status(404).json({ error: 'Licença não encontrada' });
        await db.execute(`
            UPDATE licenses
            SET bound_user = NULL, bound_at = NULL, activated_at = NULL, expires_at = NULL
            WHERE license_key = ?
        `, [key]);
        await db.addLog(req.user.id, 'LICENSE_UNBIND', `Desvinculou usuário da licença: ${key}`, key, req.ip);
        res.json({ message: '✅ Vínculo removido', license_key: key });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});


/** DELETE /api/admin/licenses/:key */
router.delete('/licenses/:key', requireAuth, async (req, res) => {
    const key = req.params.key.toUpperCase();
    if (!(await canAccess(req, key))) return res.status(403).json({ error: 'Sem permissão' });
    try {
        // Cleanup associated monitoring data
        // 1. Get associated lovable_user_ids
        const [accRows] = await db.execute('SELECT lovable_user_id FROM lovable_accounts WHERE license_key = ?', [key]);
        const userIds = accRows.map(a => a.lovable_user_id).filter(Boolean);

        // 2. Delete main data
        await db.execute('DELETE FROM licenses WHERE license_key = ?', [key]);
        await db.execute('DELETE FROM lovable_accounts WHERE license_key = ?', [key]);
        await db.execute('DELETE FROM lovable_credit_history WHERE license_key = ?', [key]);
        await db.execute('DELETE FROM extension_errors WHERE license_key = ?', [key]);
        await db.execute('DELETE FROM extension_heartbeats WHERE license_key = ?', [key]);
        await db.execute('DELETE FROM license_validation_logs WHERE license_key = ?', [key]);

        // 3. Clean projects only if they are not linked to any OTHER active license
        if (userIds.length > 0) {
            for (const uid of userIds) {
                const [others] = await db.execute('SELECT id FROM lovable_accounts WHERE lovable_user_id = ?', [uid]);
                if (others.length === 0) {
                    await db.execute('DELETE FROM lovable_projects WHERE lovable_user_id = ?', [uid]);
                    await db.execute('DELETE FROM lovable_credit_history WHERE lovable_user_id = ?', [uid]);
                }
            }
        }

        await db.addLog(req.user.id, 'LICENSE_DELETE', `Deletou licença e dados de monitoramento: ${key}`, key, req.ip);
        res.json({ message: '✅ Licença e dados de monitoramento deletados com exatidão', license_key: key });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/** 
 * GET /api/admin/analytics/credits 
 * Resumo de economia e uso de créditos Lovable
 * Superadmins vêm tudo, revendedores vêm apenas suas licenças.
 */
router.get('/analytics/credits', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        // 1. KPIs Totais (Filtrados por dono se não for superadmin)
        let queryKPIs = `
            SELECT 
                SUM(p.edit_count) as total_edits, 
                SUM(p.message_count) as total_messages,
                SUM(p.credit_total) as total_credits
            FROM lovable_projects p
            JOIN lovable_accounts a ON p.lovable_user_id = a.lovable_user_id
            JOIN licenses l ON a.license_key = l.license_key
        `;
        let paramsKPIs = [];
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryKPIs += ` WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            paramsKPIs = ownerIds;
        }
        const [[{ total_edits, total_messages, total_credits }]] = await db.execute(queryKPIs, paramsKPIs);

        // 2. Histórico de uso (últimos 14 dias)
        let queryHistory = `
            SELECT 
                DATE(h.recorded_at) as date,
                SUM(h.credits_daily_used) as credits_used,
                COUNT(DISTINCT h.lovable_user_id) as active_users
            FROM lovable_credit_history h
            JOIN licenses l ON h.license_key = l.license_key
            WHERE h.recorded_at >= NOW() - INTERVAL 14 DAY
        `;
        let paramsHistory = [];
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryHistory += ` AND l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            paramsHistory = ownerIds;
        }
        queryHistory += " GROUP BY DATE(h.recorded_at) ORDER BY date ASC";
        const [history] = await db.execute(queryHistory, paramsHistory);

        // 3. Top 10 contas (Filtrado por dono)
        let queryTop = `
            SELECT 
                la.lovable_name, la.lovable_email, la.workspace_plan,
                la.credits_daily_used, la.credits_daily_limit,
                (SELECT SUM(edit_count) FROM lovable_projects WHERE lovable_user_id = la.lovable_user_id) as total_edits
            FROM lovable_accounts la
            JOIN licenses l ON la.license_key = l.license_key
        `;
        let paramsTop = [];
        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const ownerIds = [userId, ...descendantIds];
            queryTop += ` WHERE l.owner_id IN (${ownerIds.map(() => '?').join(',')})`;
            paramsTop = ownerIds;
        }
        queryTop += " ORDER BY total_edits DESC LIMIT 10";
        const [topSavings] = await db.execute(queryTop, paramsTop);

        res.json({
            summary: {
                total_edits: total_edits || 0,
                total_messages: total_messages || 0,
                total_credits_synced: total_credits || 0,
                estimated_savings_credits: (total_edits || 0) + (total_messages || 0)
            },
            history,
            top_savings: topSavings
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// ── AUDIT LOGS (apenas superadmin) ──────────────────────────────

/** GET /api/admin/audit-logs — Histórico de ações (Superadmin vê tudo, revendedor vê apenas o dele) */
router.get('/audit-logs', requireAuth, async (req, res) => {
    try {
        const isSuperAdmin = ['superadmin', 'admin'].includes(req.user.role?.toLowerCase());
        const userId = req.user.id;

        let query = `
            SELECT a.*, u.username as performer_name, u.role as performer_role
            FROM audit_logs a
            LEFT JOIN users u ON a.user_id = u.id
        `;
        let params = [];

        if (!isSuperAdmin) {
            const descendantIds = await getDescendantIds(userId);
            const targetIds = [userId, ...descendantIds];
            query += ` WHERE a.user_id IN (${targetIds.map(() => '?').join(',')})`;
            params = targetIds;
        }

        query += " ORDER BY a.created_at DESC LIMIT 500";

        const [logs] = await db.execute(query, params);
        res.json({ logs });
    } catch (err) {
        console.error('[AUDIT LOGS ERROR]', err);
        res.status(500).json({ error: err.message });
    }
});

/** GET /api/admin/my-credits — Retorna o saldo do revendedor logado */
router.get('/my-credits', requireAuth, async (req, res) => {
    try {
        const [rows] = await db.execute('SELECT credits FROM users WHERE id = ?', [req.user.id]);
        res.json({ credits: rows[0]?.credits || 0 });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;
