// /js/manage-task.js

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

// 인증 확인
ensureAuthenticated();

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 taskForm = document.getElementById('taskForm');
taskForm?.addEventListener('submit', async e => {
  e.preventDefault();
  const body = {
    category: document.getElementById('category').value.trim(),
    subcategory: document.getElementById('subcategory').value.trim(),
    task_name: document.getElementById('task_name').value.trim(),
    description: document.getElementById('description').value.trim()
  };

  if (!body.category || !body.task_name) {
    return alert('필수 항목을 입력하세요');
  }

  try {
    const res = await fetch(`${API}/tasks`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(body)
    });
    const result = await res.json();
    if (res.ok && result.success) {
      alert('✅ 등록 완료');
      taskForm.reset();
      loadTasks();
    } else {
      alert('❌ 실패: ' + (result.error || '알 수 없는 오류'));
    }
  } catch (err) {
    alert('🚨 서버 오류: ' + err.message);
  }
});

async function loadTasks() {
  const tbody = document.getElementById('taskTableBody');
  tbody.innerHTML = '<tr><td colspan="6">불러오는 중...</td></tr>';
  try {
    const res = await fetch(`${API}/tasks`, {
      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, [
          'task_id', 'category', 'subcategory', 'task_name', 'description'
        ], async t => {
          if (!confirm('삭제하시겠습니까?')) return;
          try {
            const delRes = await fetch(`${API}/tasks/${t.task_id}`, {
              method: 'DELETE',
              headers: getAuthHeaders()
            });
            if (delRes.ok) {
              alert('✅ 삭제 완료');
              loadTasks();
            } else {
              alert('❌ 삭제 실패');
            }
          } catch (err) {
            alert('🚨 삭제 중 오류: ' + err.message);
          }
        });
        tbody.appendChild(row);
      });
    } else {
      tbody.innerHTML = '<tr><td colspan="6">데이터 형식 오류</td></tr>';
    }
  } catch (err) {
    tbody.innerHTML = '<tr><td colspan="6">로드 실패: ' + err.message + '</td></tr>';
  }
}

window.addEventListener('DOMContentLoaded', loadTasks);