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

function createRow(item, cols, delHandler) {
  const tr = document.createElement('tr');
  cols.forEach(key => {
    const td = document.createElement('td');
    td.textContent = item[key];
    tr.appendChild(td);
  });
  const delBtn = document.createElement('button');
  delBtn.textContent = '삭제';
  delBtn.className = 'btn-delete';
  delBtn.onclick = () => delHandler(item);
  const td = document.createElement('td');
  td.appendChild(delBtn);
  tr.appendChild(td);
  return tr;
}

const form = document.getElementById('issueTypeForm');
form?.addEventListener('submit', async e => {
  e.preventDefault();
  const body = {
    category: document.getElementById('category').value,
    subcategory: document.getElementById('subcategory').value
  };
  try {
    const res = await fetch(`${API}/issue-types`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(body)
    });
    const result = await res.json();
    if (res.ok && result.success) {
      alert('✅ 등록 완료');
      form.reset();
      loadIssueTypes();
    } else {
      alert('❌ 실패: ' + (result.error || '알 수 없는 오류'));
    }
  } catch (err) {
    alert('🚨 서버 오류: ' + err.message);
  }
});

async function loadIssueTypes() {
  const tbody = document.getElementById('issueTypeTableBody');
  tbody.innerHTML = '<tr><td colspan="4">불러오는 중...</td></tr>';
  try {
    const res = await fetch(`${API}/issue-types`, { 
      headers: getAuthHeaders() 
    });
    const list = await res.json();
    tbody.innerHTML = '';
    
    if (Array.isArray(list)) {
      list.forEach(item => {
        const row = createRow(item, ['issue_type_id', 'category', 'subcategory'], async t => {
          if (!confirm('삭제하시겠습니까?')) return;
          try {
            const delRes = await fetch(`${API}/issue-types/${t.issue_type_id}`, {
              method: 'DELETE',
              headers: getAuthHeaders()
            });
            if (delRes.ok) {
              loadIssueTypes();
            } else {
              alert('삭제 실패');
            }
          } catch (err) {
            alert('삭제 중 오류: ' + err.message);
          }
        });
        tbody.appendChild(row);
      });
    } else {
      tbody.innerHTML = '<tr><td colspan="4">데이터 형식 오류</td></tr>';
    }
  } catch (err) {
    tbody.innerHTML = '<tr><td colspan="4">로드 실패: ' + err.message + '</td></tr>';
  }
}

document.addEventListener('DOMContentLoaded', () => {
  loadIssueTypes();
});