/**
 * Security Module
 * Gerenciamento de configurações de segurança por site
 */
const Security = {
    // Site atualmente selecionado
    currentSiteId: null,
    currentConfig: null,
    currentLogs: [],
    
    /**
     * Inicialização
     */
    init() {
        // Listener para mostrar/ocultar duração no modal de IP
        const ipTypeSelect = document.getElementById('add-ip-type');
        if (ipTypeSelect) {
            ipTypeSelect.addEventListener('change', (e) => {
                const durationGroup = document.getElementById('add-ip-duration-group');
                if (durationGroup) {
                    durationGroup.style.display = e.target.value === 'temp_block' ? 'block' : 'none';
                }
            });
        }
    },
    
    /**
     * Carrega configurações de segurança de um site
     */
    async loadConfig(siteId) {
        if (!siteId) return;
        this.currentSiteId = siteId;
        
        try {
            const data = await Api.get(`security-config&site_id=${siteId}`);
            
            if (data.status === 'success') {
                this.currentConfig = data.data.config || {};
                this.renderConfig(this.currentConfig);
                this.renderIpRules(data.data.ip_rules || []);
                return data.data;
            }
        } catch (error) {
            console.error('Security config error:', error);
            // Configuração padrão se não existir
            this.currentConfig = this.getDefaultConfig();
            this.renderConfig(this.currentConfig);
        }
        return null;
    },
    
    /**
     * Retorna configuração padrão
     */
    getDefaultConfig() {
        return {
            rate_limit_enabled: 0,
            rate_limit_requests: 100,
            rate_limit_window: 60,
            rate_limit_block_duration: 3600,
            antibot_enabled: 0,
            antibot_check_useragent: 1,
            antibot_check_referrer: 0,
            antibot_check_javascript: 1,
            antibot_captcha_enabled: 0,
            ddos_enabled: 0,
            ddos_max_connections: 50,
            ddos_suspicious_threshold: 10,
            ddos_block_duration: 7200,
            gov_token: '',
            gov_token_expires_at: null,
            gov_token_auto_refresh: 0,
            block_devtools: 0,
            block_right_click: 1,
            block_view_source: 1,
            block_copy: 0
        };
    },
    
    /**
     * Renderiza configurações no formulário
     */
    renderConfig(config) {
        // Rate Limiting
        this.setCheckbox('sec-rate-enabled', config.rate_limit_enabled);
        this.setValue('sec-rate-max-requests', config.rate_limit_requests || 100);
        this.setValue('sec-rate-window', config.rate_limit_window || 60);
        this.setValue('sec-rate-block-duration', config.rate_limit_block_duration || 3600);
        
        // Anti-Bot
        this.setCheckbox('sec-antibot-enabled', config.antibot_enabled);
        this.setCheckbox('sec-antibot-useragent', config.antibot_check_useragent);
        this.setCheckbox('sec-antibot-referrer', config.antibot_check_referrer);
        this.setCheckbox('sec-antibot-javascript', config.antibot_check_javascript);
        this.setCheckbox('sec-antibot-captcha', config.antibot_captcha_enabled);
        
        // DDoS
        this.setCheckbox('sec-ddos-enabled', config.ddos_enabled);
        this.setValue('sec-ddos-max-connections', config.ddos_max_connections || 50);
        this.setValue('sec-ddos-threshold', config.ddos_suspicious_threshold || 10);
        this.setValue('sec-ddos-block-duration', config.ddos_block_duration || 7200);
        
        // Token GOV
        this.setCheckbox('sec-token-enabled', config.gov_token ? 1 : 0);
        this.setValue('sec-token-value', config.gov_token || '');
        if (config.gov_token_expires_at) {
            this.setValue('sec-token-expiry', config.gov_token_expires_at.slice(0, 16));
        }
        this.setCheckbox('sec-token-auto-refresh', config.gov_token_auto_refresh);
        
        // Bloqueio DevTools
        this.setCheckbox('sec-devtools-enabled', config.block_devtools);
        this.setCheckbox('sec-devtools-f12', config.block_devtools);
        this.setCheckbox('sec-devtools-rightclick', config.block_right_click);
        this.setCheckbox('sec-devtools-viewsource', config.block_view_source);
        this.setCheckbox('sec-devtools-copy', config.block_copy);
    },
    
    /**
     * Renderiza lista de regras de IP
     */
    renderIpRules(rules) {
        const container = document.getElementById('sec-ip-rules-list');
        if (!container) return;
        
        if (!rules || !rules.length) {
            container.innerHTML = `
                <div class="list-group-item text-muted text-center small py-3">
                    <i class="fas fa-info-circle me-1"></i>Nenhuma regra de IP configurada
                </div>
            `;
            return;
        }
        
        container.innerHTML = rules.map(rule => {
            const typeConfig = {
                'whitelist': { class: 'success', icon: 'check', label: 'Liberado' },
                'blacklist': { class: 'danger', icon: 'ban', label: 'Bloqueado' },
                'temp_block': { class: 'warning', icon: 'clock', label: 'Temp.' }
            };
            const cfg = typeConfig[rule.rule_type] || typeConfig['blacklist'];
            
            return `
                <div class="list-group-item d-flex justify-content-between align-items-center py-2">
                    <div>
                        <code class="small">${rule.ip_address}</code>
                        <span class="badge bg-${cfg.class} ms-2">
                            <i class="fas fa-${cfg.icon} me-1"></i>${cfg.label}
                        </span>
                    </div>
                    <button class="btn btn-sm btn-outline-danger" onclick="Security.removeIpRule(${rule.id})" title="Remover">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `;
        }).join('');
    },
    
    /**
     * Salva configurações de segurança
     */
    async saveConfig(siteId) {
        siteId = siteId || this.currentSiteId;
        if (!siteId) {
            UI.toast('Selecione um site primeiro', 'warning');
            return;
        }
        
        const config = {
            // Rate Limiting
            rate_limit_enabled: this.getCheckbox('sec-rate-enabled'),
            rate_limit_requests: this.getInt('sec-rate-max-requests'),
            rate_limit_window: this.getInt('sec-rate-window'),
            rate_limit_block_duration: this.getInt('sec-rate-block-duration'),
            
            // Anti-Bot
            antibot_enabled: this.getCheckbox('sec-antibot-enabled'),
            antibot_check_useragent: this.getCheckbox('sec-antibot-useragent'),
            antibot_check_referrer: this.getCheckbox('sec-antibot-referrer'),
            antibot_check_javascript: this.getCheckbox('sec-antibot-javascript'),
            antibot_captcha_enabled: this.getCheckbox('sec-antibot-captcha'),
            
            // DDoS
            ddos_enabled: this.getCheckbox('sec-ddos-enabled'),
            ddos_max_connections: this.getInt('sec-ddos-max-connections'),
            ddos_suspicious_threshold: this.getInt('sec-ddos-threshold'),
            ddos_block_duration: this.getInt('sec-ddos-block-duration'),
            
            // Token GOV
            gov_token: this.getCheckbox('sec-token-enabled') ? this.getValue('sec-token-value') : '',
            gov_token_expires_at: this.getValue('sec-token-expiry') || null,
            gov_token_auto_refresh: this.getCheckbox('sec-token-auto-refresh'),
            
            // Bloqueio DevTools
            block_devtools: this.getCheckbox('sec-devtools-f12'),
            block_right_click: this.getCheckbox('sec-devtools-rightclick'),
            block_view_source: this.getCheckbox('sec-devtools-viewsource'),
            block_copy: this.getCheckbox('sec-devtools-copy')
        };
        
        try {
            const data = await Api.post(`security-config&site_id=${siteId}`, config);
            
            if (data.status === 'success') {
                this.showStatus('security-status');
                UI.toast('Configurações de segurança salvas!', 'success');
            } else {
                UI.toast(data.message || 'Erro ao salvar', 'error');
            }
        } catch (error) {
            console.error('Save security config error:', error);
            UI.toast('Erro ao salvar configurações', 'error');
        }
    },
    
    /**
     * Mostra modal para adicionar regra de IP
     */
    showAddIpModal() {
        // Limpar campos
        this.setValue('add-ip-address', '');
        this.setValue('add-ip-type', 'blacklist');
        this.setValue('add-ip-duration', 60);
        this.setValue('add-ip-reason', '');
        document.getElementById('add-ip-duration-group').style.display = 'none';
        
        // Abrir modal
        const modal = new bootstrap.Modal(document.getElementById('modal-add-ip'));
        modal.show();
    },
    
    /**
     * Adiciona regra de IP
     */
    async addIpRule() {
        if (!this.currentSiteId) {
            UI.toast('Selecione um site primeiro', 'warning');
            return;
        }
        
        const ip = this.getValue('add-ip-address');
        const ruleType = this.getValue('add-ip-type');
        const reason = this.getValue('add-ip-reason');
        const duration = ruleType === 'temp_block' ? this.getInt('add-ip-duration') : null;
        
        if (!ip) {
            UI.toast('Informe o endereço IP', 'warning');
            return;
        }
        
        // Validação simples de IP
        const ipRegex = /^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/;
        if (!ipRegex.test(ip)) {
            UI.toast('Formato de IP inválido', 'warning');
            return;
        }
        
        try {
            const data = await Api.post(`security-ip-rules&site_id=${this.currentSiteId}`, {
                ip_address: ip,
                rule_type: ruleType,
                reason: reason,
                duration_minutes: duration
            });
            
            if (data.status === 'success') {
                UI.toast('Regra de IP adicionada', 'success');
                // Fechar modal
                bootstrap.Modal.getInstance(document.getElementById('modal-add-ip'))?.hide();
                // Recarregar lista
                this.loadConfig(this.currentSiteId);
            } else {
                UI.toast(data.message || 'Erro ao adicionar', 'error');
            }
        } catch (error) {
            console.error('Add IP rule error:', error);
            UI.toast('Erro ao adicionar regra de IP', 'error');
        }
    },
    
    /**
     * Remove regra de IP
     */
    async removeIpRule(ruleId) {
        if (!confirm('Remover esta regra de IP?')) return;
        
        try {
            const data = await Api.delete(`security-ip-rules&site_id=${this.currentSiteId}&rule_id=${ruleId}`);
            
            if (data.status === 'success') {
                UI.toast('Regra removida', 'success');
                this.loadConfig(this.currentSiteId);
            } else {
                UI.toast(data.message || 'Erro ao remover', 'error');
            }
        } catch (error) {
            console.error('Remove IP rule error:', error);
            UI.toast('Erro ao remover regra', 'error');
        }
    },
    
    /**
     * Carrega logs de segurança
     */
    async loadLogs(siteId) {
        siteId = siteId || this.currentSiteId;
        if (!siteId) return;
        
        try {
            const data = await Api.get(`security-logs&site_id=${siteId}`);
            
            if (data.status === 'success') {
                this.currentLogs = data.data.logs || [];
                this.renderLogs(this.currentLogs);
                
                // Abrir modal
                const modal = new bootstrap.Modal(document.getElementById('modal-security-logs'));
                modal.show();
            }
        } catch (error) {
            console.error('Load security logs error:', error);
            UI.toast('Erro ao carregar logs', 'error');
        }
    },
    
    /**
     * Renderiza logs de segurança
     */
    renderLogs(logs) {
        const tbody = document.getElementById('security-logs-body');
        if (!tbody) return;
        
        if (!logs || !logs.length) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" class="text-center text-muted py-4">
                        <i class="fas fa-info-circle me-1"></i>Nenhum log de segurança
                    </td>
                </tr>
            `;
            return;
        }
        
        const typeConfig = {
            'rate_limit': { class: 'warning', label: 'Rate Limit' },
            'bot_detected': { class: 'danger', label: 'Bot Detectado' },
            'ddos_attack': { class: 'danger', label: 'DDoS' },
            'ip_blocked': { class: 'dark', label: 'IP Bloqueado' },
            'devtools': { class: 'info', label: 'DevTools' },
            'suspicious': { class: 'warning', label: 'Suspeito' }
        };
        
        tbody.innerHTML = logs.map(log => {
            const time = log.created_at ? new Date(log.created_at).toLocaleString('pt-BR') : '-';
            const cfg = typeConfig[log.event_type] || { class: 'secondary', label: log.event_type };
            
            return `
                <tr>
                    <td class="small">${time}</td>
                    <td><span class="badge bg-${cfg.class}">${cfg.label}</span></td>
                    <td><code class="small">${log.ip_address || '-'}</code></td>
                    <td class="small text-truncate" style="max-width: 200px;">${log.details || '-'}</td>
                </tr>
            `;
        }).join('');
    },
    
    /**
     * Filtra logs por tipo
     */
    filterLogs() {
        const filterType = this.getValue('logs-filter-type');
        
        if (!filterType) {
            this.renderLogs(this.currentLogs);
            return;
        }
        
        const filtered = this.currentLogs.filter(log => log.event_type === filterType);
        this.renderLogs(filtered);
    },
    
    /**
     * Limpa logs de segurança
     */
    async clearLogs() {
        if (!confirm('Tem certeza que deseja limpar todos os logs de segurança?')) return;
        
        try {
            const data = await Api.delete(`security-logs&site_id=${this.currentSiteId}`);
            
            if (data.status === 'success') {
                UI.toast('Logs limpos', 'success');
                this.currentLogs = [];
                this.renderLogs([]);
            } else {
                UI.toast(data.message || 'Erro ao limpar logs', 'error');
            }
        } catch (error) {
            console.error('Clear logs error:', error);
            UI.toast('Erro ao limpar logs', 'error');
        }
    },
    
    /**
     * Toggle visibilidade do token
     */
    toggleTokenVisibility() {
        const input = document.getElementById('sec-token-value');
        const icon = document.getElementById('sec-token-eye');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    },
    
    /**
     * Mostra status de sucesso temporário
     */
    showStatus(elementId) {
        const el = document.getElementById(elementId);
        if (!el) return;
        
        el.style.display = 'inline';
        setTimeout(() => {
            el.style.display = 'none';
        }, 3000);
    },
    
    // ========== HELPERS ==========
    
    setValue(id, value) {
        const el = document.getElementById(id);
        if (el) el.value = value ?? '';
    },
    
    getValue(id) {
        const el = document.getElementById(id);
        return el ? el.value : '';
    },
    
    getInt(id) {
        return parseInt(this.getValue(id)) || 0;
    },
    
    setCheckbox(id, checked) {
        const el = document.getElementById(id);
        if (el) el.checked = !!parseInt(checked);
    },
    
    getCheckbox(id) {
        const el = document.getElementById(id);
        return el ? (el.checked ? 1 : 0) : 0;
    }
};

// Inicializar ao carregar
document.addEventListener('DOMContentLoaded', () => Security.init());
