/* ─────────────────────────────────────────────────────────────
    04  DB 저장
───────────────────────────────────────────────────────────── */
async function dbLoadFiles() {
  try {
    const d = await api('GET', '/api/database/files');
    const list = document.getElementById('file-list');
    if (d.files?.length) {
      list.innerHTML = d.files.map(f => `
        <div class="fitem" onclick="selectFile('${esc(f)}',this)">
          <span>📄</span><span>${esc(f)}</span>
        </div>
      `).join('');
    } else {
      list.innerHTML = '<span class="placeholder">CSV 파일이 없습니다</span>';
    }
  } catch (e) { alert('목록 로드 실패: ' + e.message); }
}

function selectFile(name, el) {
  document.querySelectorAll('.fitem').forEach(i => i.classList.remove('sel'));
  el.classList.add('sel');
  document.getElementById('sel-csv').value = name;
}

async function dbImport() {
  const fileName = document.getElementById('sel-csv').value.trim();
  if (!fileName) { alert('파일을 선택하세요.'); return; }
  // experion_ 으로 시작하면 일반 크롤 CSV, 그 외는 노드맵 CSV (서버명_timestamp.csv)
  const serverHostName = fileName.startsWith('experion_') ? '' : fileName.split('_')[0];
  const truncate = document.querySelector('input[name="import-mode"]:checked').value === 'truncate';
  if (truncate && !confirm('기존 데이터를 모두 삭제하고 새로 저장합니다.\n계속하시겠습니까?')) return;
  setGlobal('busy', 'DB 저장 중');
  try {
    const d = await api('POST', '/api/database/import', { fileName, serverHostName, truncate });
    const isNodeMap = !!serverHostName;
    const lines = [
      { c: d.success ? 'ok' : 'err', t: (d.success ? '✅ ' : '❌ ') + d.message }
    ];
    if (d.success && isNodeMap) {
      lines.push({ c: 'inf', t: `   raw_node_map  : ${d.count}건` });
      lines.push({ c: 'inf', t: `   node_map_master: ${d.masterCount}건` });
    } else if (d.success) {
      lines.push({ c: 'inf', t: `   저장된 레코드 : ${d.count}건` });
    }
    log('db-log', lines);
    setGlobal(d.success ? 'ok' : 'err', d.success ? 'DB 저장 완료' : '저장 실패');
    if (d.success) await dbQuery();
  } catch (e) {
    log('db-log', [{ c: 'err', t: '❌ ' + e.message }]);
    setGlobal('err', '오류');
  }
}

async function dbQuery() {
  const limit = parseInt(document.getElementById('db-limit').value) || 100;
  setGlobal('busy', 'DB 조회');
  try {
    const d = await api('GET', `/api/database/records?limit=${limit}`);

    const stats = document.getElementById('db-stats');
    stats.classList.remove('hidden');
    stats.innerHTML = `
      <div class="stat"><div class="sv">${d.total.toLocaleString()}</div><div class="sk">전체 레코드</div></div>
      <div class="stat"><div class="sv">${(d.records||[]).length}</div><div class="sk">현재 조회</div></div>
    `;

    const tbl = document.getElementById('db-table');
    tbl.classList.remove('hidden');
    if (d.records?.length) {
      tbl.innerHTML = `
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Node ID</th>
              <th>Value</th>
              <th>Status</th>
              <th>수집 시각</th>
              <th>Session</th>
            </tr>
          </thead>
          <tbody>
            ${d.records.map(r => `
              <tr>
                <td class="mut">${r.id}</td>
                <td style="font-size:11px">${esc(r.nodeId)}</td>
                <td class="val">${esc(r.value ?? 'null')}</td>
                <td><span class="${r.statusCode === 'Good' ? 'bg' : 'br'}">${esc(r.statusCode)}</span></td>
                <td>${new Date(r.collectedAt).toLocaleString('ko-KR')}</td>
                <td class="mut" style="font-size:10px">${esc(r.sessionId ?? '-')}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      `;
    } else {
      tbl.innerHTML = '<div style="padding:20px;color:var(--t2)">저장된 레코드가 없습니다.</div>';
    }
    setGlobal('ok', `${d.total}건`);
  } catch (e) { setGlobal('err', '조회 실패'); }
}
