/**
 * Страница «Базы данных сервисов» (FR-068, FR-090, FR-093).
 */
(function() {
    const API = '/api/v1/admin';
    let dbCache = [];
    let showSystem = false;
    let platformDatabase = null;

    function req(method, url, body) {
        const opts = { method, headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin' };
        if (body) opts.body = JSON.stringify(body);
        const fetchFn = window.cascad360Fetch || fetch;
        return fetchFn(url, opts).then(r => r.json());
    }

    function studioUrl(datasourceId, databaseName) {
        return '/admin/db-studio?datasource_id=' + encodeURIComponent(datasourceId) +
            '&database=' + encodeURIComponent(databaseName);
    }

    function formatSize(bytes) {
        if (bytes == null) return '—';
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / 1048576).toFixed(1) + ' MB';
    }

    window.loadBindings = function() {
        const el = document.getElementById('bindingsContainer');
        el.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary"></div></div>';
        req('GET', API + '/databases').then(data => {
            if (!data.success) {
                el.innerHTML = '<div class="alert alert-danger">' + (data.error || 'Ошибка загрузки') + '</div>';
                return;
            }
            const list = data.databases || [];
            if (list.length === 0) {
                el.innerHTML = '<p class="text-muted mb-0">Нет привязок. Настройте БД для сервиса справа.</p>';
                return;
            }
            let table = '<table class="table table-sm"><thead><tr><th>Сервис</th><th>Источник</th><th>База</th><th>Тип</th><th>Действия</th></tr></thead><tbody>';
            list.forEach(b => {
                table += '<tr><td>' + (b.service_name || '') + '</td><td>' + (b.datasource_id || '') + '</td><td>' + (b.database_name || '') + '</td><td>' + (b.database_type || '') + '</td><td class="text-nowrap">' +
                    '<a class="btn btn-sm btn-outline-primary me-1" href="' + studioUrl(b.datasource_id, b.database_name) + '">Открыть в студии</a>' +
                    '<button class="btn btn-sm btn-outline-danger" onclick="deleteBinding(' + b.id + ')">Удалить</button></td></tr>';
            });
            table += '</tbody></table>';
            el.innerHTML = table;
        });
    };

    window.loadServices = function() {
        req('GET', API + '/services/list').then(data => {
            const sel = document.getElementById('setupServiceName');
            sel.innerHTML = '<option value="">— Выберите сервис —</option>';
            if (data.success && data.services) {
                Object.keys(data.services).sort().forEach(name => {
                    sel.appendChild(new Option(name, name));
                });
            }
            const params = new URLSearchParams(window.location.search);
            const preselect = params.get('service');
            if (preselect && sel.querySelector('option[value="' + preselect.replace(/"/g, '') + '"]')) {
                sel.value = preselect;
            }
        });
    };

    window.loadDatasources = function() {
        req('GET', API + '/datasources').then(data => {
            const sel = document.getElementById('setupDatasourceId');
            sel.innerHTML = '';
            if (data.success && data.datasources) {
                (data.datasources || []).forEach(ds => {
                    sel.appendChild(new Option(ds.id + ' (' + ds.type + ')', ds.id));
                });
            }
            if (sel.options.length === 0) sel.appendChild(new Option('core', 'core'));
        });
    };

    function renderDbOptions(filter) {
        const sel = document.getElementById('setupExistingDb');
        const meta = document.getElementById('setupDbMeta');
        sel.innerHTML = '<option value="">— Выберите базу —</option>';
        const f = (filter || '').toLowerCase();
        dbCache.forEach(db => {
            const name = typeof db === 'string' ? db : db.name;
            if (f && name.toLowerCase().indexOf(f) < 0) return;
            const label = typeof db === 'string' ? name : (
                name + (db.is_platform ? ' [ядро]' : (db.system_reason === 'platform' ? ' [ядро]' : '')) +
                (db.table_count != null ? ' (' + db.table_count + ' tbl)' : '') +
                (db.size_bytes != null ? ' ' + formatSize(db.size_bytes) : '') +
                (db.is_system && !db.is_platform && db.system_reason !== 'platform' ? ' [system]' : '')
            );
            sel.appendChild(new Option(label, name));
        });
        if (meta) {
            meta.textContent = dbCache.length ? 'Доступно: ' + dbCache.length : '';
        }
    }

    function updatePlatformHint() {
        const hint = document.getElementById('platformDbHint');
        if (!hint) return;
        if (platformDatabase && platformDatabase.database_name) {
            hint.textContent = 'БД ядра: ' + platformDatabase.datasource_id + ' / ' +
                platformDatabase.database_name + ' (' + platformDatabase.database_type + ')';
        } else {
            hint.textContent = 'БД ядра не настроена в конфиге.';
        }
    }

    function loadDatabasesOnDatasource() {
        const ds = document.getElementById('setupDatasourceId').value;
        if (!ds) return;
        const sel = document.getElementById('setupExistingDb');
        sel.innerHTML = '<option value="">Загрузка...</option>';
        const params = new URLSearchParams();
        params.set('include_platform', 'true');
        if (showSystem) params.set('include_system', 'true');
        req('GET', API + '/databases/datasource/' + encodeURIComponent(ds) + '/list?' + params.toString()).then(data => {
            dbCache = data.success ? (data.databases || []) : [];
            platformDatabase = data.platform_database || null;
            updatePlatformHint();
            renderDbOptions(document.getElementById('setupDbSearch')?.value || '');
        });
    }

    window.toggleShowSystem = function(checked) {
        showSystem = !!checked;
        loadDatabasesOnDatasource();
    };

    window.runSetup = function() {
        const serviceName = document.getElementById('setupServiceName').value;
        if (!serviceName) {
            showSetupMessage('Выберите сервис', 'warning');
            return;
        }
        const action = document.querySelector('input[name="setupAction"]:checked').value;
        const datasourceId = document.getElementById('setupDatasourceId').value;
        const databaseType = document.getElementById('setupDbType').value;
        let databaseName = '';
        let body = { action: action === 'use_platform' ? 'use_existing' : action, database_type: databaseType, datasource_id: datasourceId };
        if (action === 'use_platform') {
            if (!platformDatabase || !platformDatabase.database_name) {
                showSetupMessage('БД ядра не настроена', 'warning');
                return;
            }
            body.database_name = platformDatabase.database_name;
            body.database_type = platformDatabase.database_type || databaseType;
            body.datasource_id = platformDatabase.datasource_id || datasourceId;
        } else if (action === 'create') {
            databaseName = document.getElementById('setupDatabaseName').value.trim();
            if (!databaseName) {
                showSetupMessage('Введите имя новой базы', 'warning');
                return;
            }
            body.database_name = databaseName;
            const charsetEl = document.getElementById('setupCharset');
            const collEl = document.getElementById('setupCollation');
            if (charsetEl && charsetEl.value) body.charset = charsetEl.value;
            if (collEl && collEl.value) body.collation = collEl.value;
        } else {
            databaseName = document.getElementById('setupExistingDb').value;
            if (!databaseName) {
                showSetupMessage('Выберите существующую базу', 'warning');
                return;
            }
            body.database_name = databaseName;
            body.action = 'use_existing';
        }
        showSetupMessage('Выполняется...', 'info');
        req('POST', API + '/services/' + encodeURIComponent(serviceName) + '/database/setup', body).then(data => {
            if (data.success) {
                showSetupMessage('Настройка выполнена.', 'success');
                loadBindings();
            } else {
                showSetupMessage(data.error || 'Ошибка', 'danger');
            }
        });
    };

    window.validateSql = function() {
        const serviceName = document.getElementById('setupServiceName').value;
        if (!serviceName) {
            showSetupMessage('Выберите сервис', 'warning');
            return;
        }
        showSetupMessage('Валидация...', 'info');
        req('POST', API + '/services/' + encodeURIComponent(serviceName) + '/database/validate', {
            database_type: document.getElementById('setupDbType').value
        }).then(data => {
            if (data.success && data.validation) {
                const v = data.validation;
                let msg = v.valid ? 'Валидация пройдена.' : 'Ошибки: ' + (v.errors || []).join('; ');
                if (v.warnings && v.warnings.length) msg += ' Предупреждения: ' + v.warnings.join('; ');
                showSetupMessage(msg, v.valid ? 'success' : 'danger');
            } else {
                showSetupMessage(data.error || 'Ошибка валидации', 'danger');
            }
        });
    };

    window.installSql = function() {
        const serviceName = document.getElementById('setupServiceName').value;
        if (!serviceName) {
            showSetupMessage('Выберите сервис', 'warning');
            return;
        }
        const progressEl = document.getElementById('installProgress');
        if (progressEl) progressEl.innerHTML = '<div class="progress"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width:30%">Выполнение...</div></div>';
        showSetupMessage('Выполнение SQL...', 'info');
        req('POST', API + '/services/' + encodeURIComponent(serviceName) + '/database/install', {}).then(data => {
            if (progressEl) {
                if (data.success && data.results) {
                    let html = '<ul class="list-unstyled small mb-0">';
                    data.results.forEach(function(r, i) {
                        html += '<li>Шаг ' + (i + 1) + ': ' + (r.success ? '✓' : '✗ ' + (r.result?.message || '')) + '</li>';
                    });
                    html += '</ul>';
                    progressEl.innerHTML = html;
                } else {
                    progressEl.innerHTML = '';
                }
            }
            if (data.success) {
                showSetupMessage('SQL выполнен успешно.', 'success');
            } else {
                showSetupMessage(data.error || 'Ошибка выполнения', 'danger');
            }
        });
    };

    window.deleteBinding = function(id) {
        if (!confirm('Удалить привязку?')) return;
        req('DELETE', API + '/databases/' + id).then(data => {
            if (data.success) {
                loadBindings();
                document.getElementById('setupMessage').innerHTML = '<span class="text-success">Привязка удалена.</span>';
            } else {
                document.getElementById('setupMessage').innerHTML = '<span class="text-danger">' + (data.error || 'Ошибка') + '</span>';
            }
        });
    };

    function showSetupMessage(text, type) {
        const el = document.getElementById('setupMessage');
        el.innerHTML = '<span class="text-' + type + '">' + text + '</span>';
    }

    function syncSetupBlocks() {
        const action = document.querySelector('input[name="setupAction"]:checked')?.value || 'use_platform';
        document.getElementById('setupNewNameBlock').classList.toggle('d-none', action !== 'create');
        document.getElementById('setupExistingBlock').classList.toggle('d-none', action !== 'use_existing');
        document.getElementById('setupCharsetBlock')?.classList.toggle('d-none', action !== 'create');
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('input[name="setupAction"]').forEach(r => {
            r.addEventListener('change', function() {
                syncSetupBlocks();
                if (this.value === 'use_existing') loadDatabasesOnDatasource();
            });
        });
        document.getElementById('setupDatasourceId').addEventListener('change', function() {
            loadDatabasesOnDatasource();
        });
        const searchEl = document.getElementById('setupDbSearch');
        if (searchEl) {
            searchEl.addEventListener('input', function() {
                renderDbOptions(this.value);
            });
        }
        loadBindings();
        loadServices();
        loadDatasources();
        setTimeout(function() {
            loadDatabasesOnDatasource();
            syncSetupBlocks();
        }, 300);
    });
})();
