/**
 * JavaScript для страницы управления безопасностью (FR-032)
 */

let currentTab = 'ip-lists';
let eventsOffset = 0;
let eventsLimit = 50;

document.addEventListener('DOMContentLoaded', function() {
    loadIPLists();
    loadWAFRules();
    loadSecurityEvents();
    
    // Автообновление событий каждые 30 секунд
    setInterval(() => {
        if (currentTab === 'events') {
            loadSecurityEvents();
        }
    }, 30000);
});

function switchSecurityTab(tab) {
    currentTab = tab;
    
    // Скрываем все вкладки
    document.querySelectorAll('.tab-content').forEach(el => {
        el.style.display = 'none';
    });
    
    // Показываем выбранную вкладку
    document.getElementById(`${tab}-tab`).style.display = 'block';
    
    // Обновляем активную кнопку
    document.querySelectorAll('#securityTabs .nav-link').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // Загружаем данные для вкладки
    if (tab === 'ip-lists') {
        loadIPLists();
    } else if (tab === 'waf-rules') {
        loadWAFRules();
    } else if (tab === 'events') {
        loadSecurityEvents();
    } else if (tab === 'blocked-ips') {
        loadBlockedIPs();
    } else if (tab === 'public-auth') {
        mountPublicAuthSettings();
    }
}

function mountPublicAuthSettings() {
    const container = document.getElementById('publicAuthSettingsContainer');
    if (!container || container.dataset.mounted) return;
    if (window.PublicAuthSettingsPanel) {
        window.PublicAuthSettingsPanel.mount(container);
        container.dataset.mounted = '1';
    }
}

// === IP Lists ===

async function loadIPLists() {
    try {
        const listType = document.getElementById('ipListTypeFilter').value;
        const url = `/api/v1/admin/security/ip-lists${listType ? `?type=${listType}` : ''}`;
        const response = await fetch(url);
        const data = await response.json();
        
        if (data.success) {
            renderIPLists(data.entries);
        } else {
            showError('Ошибка загрузки IP списков: ' + (data.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка загрузки IP списков: ' + error.message);
    }
}

function renderIPLists(entries) {
    const tbody = document.getElementById('ipListsTableBody');
    if (entries.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center">Нет записей</td></tr>';
        return;
    }
    
    tbody.innerHTML = entries.map(entry => `
        <tr>
            <td>${entry.ip_address || '-'}</td>
            <td>${entry.ip_range || '-'}</td>
            <td>
                <span class="badge ${entry.list_type === 'whitelist' ? 'bg-success' : 'bg-danger'}">
                    ${entry.list_type === 'whitelist' ? 'Whitelist' : 'Blacklist'}
                </span>
            </td>
            <td>${entry.description || '-'}</td>
            <td>
                <span class="badge ${entry.enabled ? 'bg-success' : 'bg-secondary'}">
                    ${entry.enabled ? 'Включено' : 'Отключено'}
                </span>
            </td>
            <td>${new Date(entry.created_at).toLocaleString('ru-RU')}</td>
            <td>${entry.expires_at ? new Date(entry.expires_at).toLocaleString('ru-RU') : 'Бессрочно'}</td>
            <td>
                <button class="btn btn-sm btn-danger" onclick="removeIPFromList(${entry.id})">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function showAddIPModal() {
    document.getElementById('addIPForm').reset();
    new bootstrap.Modal(document.getElementById('addIPModal')).show();
}

async function addIPToList() {
    try {
        const form = document.getElementById('addIPForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const data = {
            ip_address: document.getElementById('ipAddress').value,
            ip_range: document.getElementById('ipRange').value || null,
            list_type: document.getElementById('ipListType').value,
            description: document.getElementById('ipDescription').value || null,
            expires_at: document.getElementById('ipExpiresAt').value || null
        };
        
        if (data.expires_at) {
            data.expires_at = new Date(data.expires_at).toISOString();
        }
        
        const response = await fetch('/api/v1/admin/security/ip-lists', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('addIPModal')).hide();
            loadIPLists();
            showSuccess('IP успешно добавлен в список');
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

async function removeIPFromList(ipId) {
    if (!confirm('Удалить IP из списка?')) return;
    
    try {
        const response = await fetch(`/api/v1/admin/security/ip-lists/${ipId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            loadIPLists();
            showSuccess('IP удален из списка');
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

// === WAF Rules ===

async function loadWAFRules() {
    try {
        const response = await fetch('/api/v1/admin/security/waf-rules');
        const data = await response.json();
        
        if (data.success) {
            renderWAFRules(data.rules);
        } else {
            showError('Ошибка загрузки WAF правил: ' + (data.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка загрузки WAF правил: ' + error.message);
    }
}

function renderWAFRules(rules) {
    const tbody = document.getElementById('wafRulesTableBody');
    if (rules.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center">Нет правил</td></tr>';
        return;
    }
    
    tbody.innerHTML = rules.map(rule => `
        <tr>
            <td>${rule.name}</td>
            <td><span class="badge bg-info">${rule.rule_type}</span></td>
            <td><code>${rule.pattern.substring(0, 50)}${rule.pattern.length > 50 ? '...' : ''}</code></td>
            <td>
                <span class="badge ${rule.action === 'block' ? 'bg-danger' : 'bg-warning'}">
                    ${rule.action === 'block' ? 'Блокировать' : rule.action === 'log' ? 'Логировать' : 'Перенаправить'}
                </span>
            </td>
            <td>
                <span class="badge ${getSeverityBadgeClass(rule.severity)}">
                    ${rule.severity}
                </span>
            </td>
            <td>${rule.priority}</td>
            <td>
                <span class="badge ${rule.enabled ? 'bg-success' : 'bg-secondary'}">
                    ${rule.enabled ? 'Включено' : 'Отключено'}
                </span>
            </td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="editWAFRule(${rule.id})">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteWAFRule(${rule.id})">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function showAddWAFRuleModal() {
    document.getElementById('addWAFRuleForm').reset();
    document.getElementById('wafRulePriority').value = '0';
    new bootstrap.Modal(document.getElementById('addWAFRuleModal')).show();
}

async function addWAFRule() {
    try {
        const form = document.getElementById('addWAFRuleForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const data = {
            name: document.getElementById('wafRuleName').value,
            description: document.getElementById('wafRuleDescription').value || null,
            rule_type: document.getElementById('wafRuleType').value,
            pattern: document.getElementById('wafRulePattern').value,
            action: document.getElementById('wafRuleAction').value,
            severity: document.getElementById('wafRuleSeverity').value,
            priority: parseInt(document.getElementById('wafRulePriority').value) || 0,
            match_location: document.getElementById('wafRuleMatchLocation').value
        };
        
        const response = await fetch('/api/v1/admin/security/waf-rules', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('addWAFRuleModal')).hide();
            loadWAFRules();
            showSuccess('WAF правило успешно создано');
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

async function deleteWAFRule(ruleId) {
    if (!confirm('Удалить WAF правило?')) return;
    
    try {
        const response = await fetch(`/api/v1/admin/security/waf-rules/${ruleId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            loadWAFRules();
            showSuccess('WAF правило удалено');
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

// === Security Events ===

async function loadSecurityEvents() {
    try {
        const params = new URLSearchParams({
            limit: eventsLimit,
            offset: eventsOffset
        });
        
        const eventType = document.getElementById('eventTypeFilter').value;
        const severity = document.getElementById('eventSeverityFilter').value;
        const ipAddress = document.getElementById('eventIPFilter').value;
        const resolved = document.getElementById('eventResolvedFilter').value;
        
        if (eventType) params.append('event_type', eventType);
        if (severity) params.append('severity', severity);
        if (ipAddress) params.append('ip_address', ipAddress);
        if (resolved !== '') params.append('resolved', resolved);
        
        const response = await fetch(`/api/v1/admin/security/events?${params}`);
        const data = await response.json();
        
        if (data.success) {
            renderSecurityEvents(data.events);
            document.getElementById('eventsTotal').textContent = data.total;
            updateEventsPagination(data.total);
        } else {
            showError('Ошибка загрузки событий: ' + (data.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка загрузки событий: ' + error.message);
    }
}

function renderSecurityEvents(events) {
    const tbody = document.getElementById('securityEventsTableBody');
    if (events.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center">Нет событий</td></tr>';
        return;
    }
    
    tbody.innerHTML = events.map(event => `
        <tr>
            <td><span class="badge bg-secondary">${event.event_type}</span></td>
            <td><code>${event.ip_address}</code></td>
            <td>
                <span class="badge ${getSeverityBadgeClass(event.severity)}">
                    ${event.severity}
                </span>
            </td>
            <td>${event.description || '-'}</td>
            <td><code>${event.request_path || '-'}</code></td>
            <td>${new Date(event.timestamp).toLocaleString('ru-RU')}</td>
            <td>
                <span class="badge ${event.resolved ? 'bg-success' : 'bg-warning'}">
                    ${event.resolved ? 'Решено' : 'Не решено'}
                </span>
            </td>
            <td>
                ${!event.resolved ? `
                    <button class="btn btn-sm btn-success" onclick="resolveSecurityEvent(${event.id})">
                        <i class="bi bi-check-circle"></i> Решить
                    </button>
                ` : ''}
            </td>
        </tr>
    `).join('');
}

function updateEventsPagination(total) {
    const pagination = document.getElementById('eventsPagination');
    const totalPages = Math.ceil(total / eventsLimit);
    const currentPage = Math.floor(eventsOffset / eventsLimit) + 1;
    
    let html = '';
    if (currentPage > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="changeEventsPage(${currentPage - 1})">Предыдущая</a></li>`;
    }
    for (let i = 1; i <= totalPages; i++) {
        html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
            <a class="page-link" href="#" onclick="changeEventsPage(${i})">${i}</a>
        </li>`;
    }
    if (currentPage < totalPages) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="changeEventsPage(${currentPage + 1})">Следующая</a></li>`;
    }
    
    pagination.innerHTML = html;
}

function changeEventsPage(page) {
    eventsOffset = (page - 1) * eventsLimit;
    loadSecurityEvents();
}

async function resolveSecurityEvent(eventId) {
    try {
        const response = await fetch(`/api/v1/admin/security/events/${eventId}/resolve`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            loadSecurityEvents();
            showSuccess('Событие помечено как решенное');
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

// === Blocked IPs ===

async function loadBlockedIPs() {
    // TODO: Реализовать получение списка заблокированных IP
    const tbody = document.getElementById('blockedIPsTableBody');
    tbody.innerHTML = '<tr><td colspan="4" class="text-center">Функция в разработке</td></tr>';
}

function showBlockIPModal() {
    document.getElementById('blockIPForm').reset();
    document.getElementById('blockDuration').value = '3600';
    new bootstrap.Modal(document.getElementById('blockIPModal')).show();
}

async function blockIP() {
    try {
        const form = document.getElementById('blockIPForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const data = {
            ip_address: document.getElementById('blockIPAddress').value,
            duration_seconds: parseInt(document.getElementById('blockDuration').value) || 3600
        };
        
        const response = await fetch('/api/v1/admin/security/ip-block', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('blockIPModal')).hide();
            loadBlockedIPs();
            showSuccess(`IP ${data.ip_address} заблокирован на ${data.duration_seconds} секунд`);
        } else {
            showError('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    } catch (error) {
        showError('Ошибка: ' + error.message);
    }
}

// === Утилиты ===

function getSeverityBadgeClass(severity) {
    const classes = {
        'low': 'bg-info',
        'medium': 'bg-warning',
        'high': 'bg-danger',
        'critical': 'bg-dark'
    };
    return classes[severity] || 'bg-secondary';
}

function showSuccess(message) {
    // Простое уведомление (можно заменить на toast)
    alert('✓ ' + message);
}

function showError(message) {
    alert('✗ ' + message);
}
