/**
 * Страница «БД ядра» — просмотр структуры основной БД проекта (read-only).
 */
(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {
    var root = document.getElementById('db-admin-root');
    if (!root) return;

    var datasourceId = root.dataset.datasource || 'core';
    var database = root.dataset.database || '';
    if (!database) return;

    var API = '/api/v1/admin/db';
    var listElem = document.getElementById('tables-list');
    var tableTitle = document.getElementById('table-title');
    var structureView = document.getElementById('structure-view');
    var dataView = document.getElementById('table-dataview');
    var searchInput = document.getElementById('table-search');
    var reloadBtn = document.getElementById('reload-tables-btn');
    var allTables = [];

    function ctxQuery(extra) {
      var params = new URLSearchParams({
        datasource_id: datasourceId,
        database: database
      });
      if (extra) {
        Object.keys(extra).forEach(function (k) {
          if (extra[k] !== undefined && extra[k] !== null && extra[k] !== '') {
            params.set(k, extra[k]);
          }
        });
      }
      return '?' + params.toString();
    }

    function apiGet(path) {
      return fetch(path, { credentials: 'same-origin', headers: { Accept: 'application/json' } })
        .then(function (r) { return r.json(); });
    }

    function renderTables(filter) {
      var term = (filter || '').toLowerCase();
      listElem.innerHTML = '';
      allTables.filter(function (t) {
        return !term || t.name.toLowerCase().indexOf(term) >= 0;
      }).forEach(function (t) {
        var li = document.createElement('li');
        li.className = 'list-group-item list-group-item-action';
        li.textContent = t.name + (t.type === 'view' ? ' (view)' : '');
        li.setAttribute('role', 'button');
        li.tabIndex = 0;
        li.onclick = function () { selectTable(t.name); };
        listElem.appendChild(li);
      });
      if (!listElem.children.length) {
        listElem.innerHTML = '<li class="list-group-item text-muted">Таблицы не найдены</li>';
      }
    }

    function loadTables() {
      listElem.innerHTML = '<li class="list-group-item text-muted">Загрузка...</li>';
      apiGet(API + '/tables' + ctxQuery()).then(function (data) {
        if (!data.success) {
          listElem.innerHTML = '<li class="list-group-item text-danger">' + (data.error || 'Ошибка') + '</li>';
          return;
        }
        allTables = data.tables || [];
        renderTables(searchInput ? searchInput.value : '');
      });
    }

    function selectTable(name) {
      tableTitle.textContent = 'Таблица: ' + name;
      structureView.innerHTML = '<div class="text-muted">Загрузка структуры...</div>';
      dataView.innerHTML = '';

      apiGet(API + '/table/' + encodeURIComponent(name) + '/structure' + ctxQuery()).then(function (res) {
        if (!res.success || !res.structure) {
          structureView.innerHTML = '<div class="text-danger">' + (res.error || 'Ошибка структуры') + '</div>';
          return;
        }
        var struct = res.structure;
        var html = '<p class="small text-muted">PK: ' + ((struct.primary_key || []).join(', ') || '—') + '</p>';
        html += '<table class="table table-bordered table-sm mb-2"><thead><tr><th>Колонка</th><th>Тип</th><th>NULL</th><th>PK</th><th>Default</th></tr></thead><tbody>';
        (struct.columns || []).forEach(function (col) {
          html += '<tr><td>' + col.name + '</td><td>' + (col.data_type || '') + '</td><td>' +
            (col.nullable ? 'YES' : 'NO') + '</td><td>' + (col.is_primary_key ? '✓' : '') + '</td><td>' +
            (col.default != null ? col.default : '') + '</td></tr>';
        });
        html += '</tbody></table>';
        if (struct.foreign_keys && struct.foreign_keys.length) {
          html += '<p class="small"><strong>FK:</strong> ' + struct.foreign_keys.map(function (fk) {
            return fk.column + ' → ' + fk.referenced_table + '.' + fk.referenced_column;
          }).join('; ') + '</p>';
        }
        structureView.innerHTML = html;
      });

      dataView.innerHTML = '<div class="text-muted">Загрузка данных...</div>';
      apiGet(API + '/table/' + encodeURIComponent(name) + '/rows' + ctxQuery({ page: 1, page_size: 50 })).then(function (res) {
        if (!res.success) {
          dataView.innerHTML = '<div class="text-danger">' + (res.error || 'Ошибка данных') + '</div>';
          return;
        }
        var rows = res.rows || [];
        if (!rows.length) {
          dataView.innerHTML = '<span class="text-muted">Нет данных (таблица пустая)</span>';
          return;
        }
        var cols = Object.keys(rows[0]);
        var table = document.createElement('table');
        table.className = 'table table-striped table-hover table-bordered table-sm';
        var thead = document.createElement('thead');
        var tr = document.createElement('tr');
        cols.forEach(function (col) {
          var th = document.createElement('th');
          th.textContent = col;
          tr.appendChild(th);
        });
        thead.appendChild(tr);
        table.appendChild(thead);
        var tbody = document.createElement('tbody');
        rows.forEach(function (row) {
          var rowTr = document.createElement('tr');
          cols.forEach(function (col) {
            var td = document.createElement('td');
            td.textContent = row[col] != null ? String(row[col]) : '';
            rowTr.appendChild(td);
          });
          tbody.appendChild(rowTr);
        });
        table.appendChild(tbody);
        dataView.innerHTML = '';
        dataView.appendChild(table);
        if (res.total > rows.length) {
          var info = document.createElement('p');
          info.className = 'small text-muted mt-2';
          info.textContent = 'Показано ' + rows.length + ' из ' + res.total + ' строк (read-only).';
          dataView.appendChild(info);
        }
      });
    }

    if (searchInput) {
      searchInput.addEventListener('input', function () {
        renderTables(searchInput.value);
      });
    }
    if (reloadBtn) reloadBtn.addEventListener('click', loadTables);

    loadTables();
  });
})();
