/* ─────────────────────────────────────────────────────────────
   01  인증서 관리
───────────────────────────────────────────────────────────── */
async function certCreate() {
  const clientHostName  = document.getElementById('c-host').value.trim();
  const subjectAltNames = document.getElementById('c-san').value
    .split(',').map(s => s.trim()).filter(Boolean);
  const pfxPassword = document.getElementById('c-pw').value;

  setGlobal('busy', '인증서 생성 중');
  try {
    const d = await api('POST', '/api/certificate/create', {
      clientHostName, subjectAltNames, pfxPassword
    });
    log('cert-log', [
      { c: d.success ? 'ok' : 'err', t: (d.success ? '✅ ' : '❌ ') + d.message },
      ...(d.thumbPrint ? [{ c: 'inf', t: '   Thumbprint : ' + d.thumbPrint }] : [])
    ]);
    setGlobal(d.success ? 'ok' : 'err', d.success ? '인증서 완료' : '오류');
    if (d.success) {
      document.getElementById('cert-dot').classList.add('on');
      await certStatus();
    }
  } catch (e) {
    log('cert-log', [{ c: 'err', t: '❌ ' + e.message }]);
    setGlobal('err', '오류');
  }
}

async function certStatus() {
  const clientHostName = document.getElementById('c-host').value.trim() || 'dbsvr';
  try {
    const d = await api('GET', `/api/certificate/status?clientHostName=${encodeURIComponent(clientHostName)}`);
    const box = document.getElementById('cert-disp');
    if (d.exists) {
      box.innerHTML = `
        <div class="kv"><span class="kk">상태</span><span class="kv2 ok">✅ 인증서 있음</span></div>
        <div class="kv"><span class="kk">Subject</span><span class="kv2">${esc(d.subjectName)}</span></div>
        <div class="kv"><span class="kk">만료일</span><span class="kv2">${d.notAfter ? new Date(d.notAfter).toLocaleDateString('ko-KR') : '-'}</span></div>
        <div class="kv"><span class="kk">Thumbprint</span><span class="kv2">${d.thumbPrint ? d.thumbPrint.slice(0,20)+'…' : '-'}</span></div>
        <div class="kv"><span class="kk">파일 경로</span><span class="kv2">${esc(d.filePath)}</span></div>
      `;
      document.getElementById('cert-dot').classList.add('on');
      setGlobal('ok', '인증서 확인됨');
    } else {
      box.innerHTML = `
        <div class="kv"><span class="kk">상태</span><span class="kv2 err">❌ 인증서 없음</span></div>
        <div class="kv"><span class="kk">경로</span><span class="kv2">${esc(d.filePath)}</span></div>
      `;
      setGlobal('', 'READY');
    }
  } catch {}
}
