import { API, getAuthHeaders, ensureAuthenticated } from '/js/api-config.js';

// 인증 확인
ensureAuthenticated();

// 행 생성
function createRow(item, delHandler) {
  const tr = document.createElement('tr');
  const label = `${item.material} / ${item.diameter_in} / ${item.schedule}`;
  tr.innerHTML = `
    <td>${item.spec_id}</td>
    <td>${label}</td>
    <td><button class="btn-delete">삭제</button></td>
  `;
  tr.querySelector('.btn-delete').onclick = () => delHandler(item);
  return tr;
}

// 등록
document.getElementById('specForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const material = document.getElementById('material').value.trim();
  const diameter = document.getElementById('diameter_in').value.trim();
  const schedule = document.getElementById('schedule').value.trim();

  if (!material || !diameter || !schedule) {
    return alert('모든 항목을 입력하세요.');
  }

  try {
    const res = await fetch(`${API}/pipespecs`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({ material, diameter_in: diameter, schedule })
    });
    const result = await res.json();
    if (res.ok && result.success) {
      alert('✅ 등록 완료');
      e.target.reset();
      loadSpecs();
    } else {
      alert('❌ 실패: ' + (result.error || '등록 실패'));
    }
  } catch (err) {
    alert('🚨 서버 오류: ' + err.message);
  }
});

// 불러오기
async function loadSpecs() {
  const tbody = document.getElementById('specTableBody');
  tbody.innerHTML = '<tr><td colspan="3">불러오는 중...</td></tr>';
  try {
    const res = await fetch(`${API}/pipespecs`, {
      headers: getAuthHeaders()
    });
    
    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`);
    }
    
    const list = await res.json();
    tbody.innerHTML = '';
    
    if (Array.isArray(list)) {
      list.forEach(item => {
        const row = createRow(item, async (spec) => {
          if (!confirm('삭제하시겠습니까?')) return;
          try {
            const delRes = await fetch(`${API}/pipespecs/${spec.spec_id}`, {
              method: 'DELETE',
              headers: getAuthHeaders()
            });
            if (delRes.ok) {
              loadSpecs();
            } else {
              alert('삭제 실패');
            }
          } catch (err) {
            alert('삭제 중 오류: ' + err.message);
          }
        });
        tbody.appendChild(row);
      });
    } else {
      tbody.innerHTML = '<tr><td colspan="3">데이터 형식 오류</td></tr>';
    }
  } catch (err) {
    tbody.innerHTML = '<tr><td colspan="3">로드 실패: ' + err.message + '</td></tr>';
  }
}

window.addEventListener('DOMContentLoaded', loadSpecs);