const API = '/api';

function getToken() {
  return localStorage.getItem('teamflow_token');
}

async function request(path, options = {}) {
  const token = getToken();
  const headers = { 'Content-Type': 'application/json', ...options.headers };
  if (token) headers['Authorization'] = `Bearer ${token}`;
  const res = await fetch(`${API}${path}`, { ...options, headers });
  if (res.status === 401) {
    localStorage.removeItem('teamflow_token');
    localStorage.removeItem('teamflow_user');
    window.location.href = '/login';
    throw new Error('Unauthorized');
  }
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || 'Request failed');
  return data;
}

export const api = {
  setup: {
    status: () => fetch(`${API}/setup/status`).then(r => r.json()),
    configureEmail: (data) => request('/setup/email', { method: 'POST', body: JSON.stringify(data) }),
    testEmail: (to) => request('/setup/email/test', { method: 'POST', body: JSON.stringify({ to }) }),
    createAdmin: (data) => request('/setup/admin', { method: 'POST', body: JSON.stringify(data) }),
    updateInbound: (data) => request('/setup/email/inbound', { method: 'PUT', body: JSON.stringify(data) }),
  },
  auth: {
    login: (data) => request('/auth/login', { method: 'POST', body: JSON.stringify(data) }),
    me: () => request('/auth/me'),
    update: (data) => request('/auth/me', { method: 'PUT', body: JSON.stringify(data) }),
  },
  users: {
    list: () => request('/users/'),
    create: (data) => request('/users/', { method: 'POST', body: JSON.stringify(data) }),
    update: (id, data) => request(`/users/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    resetPassword: (id, password) => request(`/users/${id}/reset-password`, { method: 'PUT', body: JSON.stringify({ password }) }),
    boardMembers: (boardId) => request(`/users/board/${boardId}`),
  },
  boards: {
    list: () => request('/boards/'),
    get: (id) => request(`/boards/${id}`),
    full: (id) => request(`/boards/${id}/full`),
    create: (data) => request('/boards/', { method: 'POST', body: JSON.stringify(data) }),
    update: (id, data) => request(`/boards/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id) => request(`/boards/${id}`, { method: 'DELETE' }),
    addMember: (id, data) => request(`/boards/${id}/members`, { method: 'POST', body: JSON.stringify(data) }),
    removeMember: (id, userId) => request(`/boards/${id}/members/${userId}`, { method: 'DELETE' }),
  },
  cards: {
    create: (listId, data) => request(`/cards/lists/${listId}/cards`, { method: 'POST', body: JSON.stringify(data) }),
    get: (id) => request(`/cards/${id}`),
    update: (id, data) => request(`/cards/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id) => request(`/cards/${id}`, { method: 'DELETE' }),
    reorder: (cards) => request('/cards/reorder', { method: 'PUT', body: JSON.stringify({ cards }) }),
    addComment: (id, content) => request(`/cards/${id}/comments`, { method: 'POST', body: JSON.stringify({ content }) }),
    createList: (boardId, title) => request(`/cards/${boardId}/lists`, { method: 'POST', body: JSON.stringify({ title }) }),
    updateList: (id, data) => request(`/cards/lists/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    reorderList: (id, position) => request(`/cards/lists/${id}/reorder`, { method: 'PUT', body: JSON.stringify({ position }) }),
    addLabel: (boardId, data) => request(`/cards/${boardId}/labels`, { method: 'POST', body: JSON.stringify(data) }),
    updateLabel: (id, data) => request(`/cards/labels/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    deleteLabel: (id) => request(`/cards/labels/${id}`, { method: 'DELETE' }),
    updateCardLabels: (id, labels) => request(`/cards/${id}/labels`, { method: 'PUT', body: JSON.stringify({ labels }) }),
    createChecklist: (cardId, title) => request(`/cards/${cardId}/checklists`, { method: 'POST', body: JSON.stringify({ title }) }),
    addChecklistItem: (checklistId, text) => request(`/cards/checklists/${checklistId}/items`, { method: 'POST', body: JSON.stringify({ text }) }),
    updateChecklistItem: (id, data) => request(`/cards/checklist-items/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    deleteChecklistItem: (id) => request(`/cards/checklist-items/${id}`, { method: 'DELETE' }),
    deleteChecklist: (id) => request(`/cards/checklists/${id}`, { method: 'DELETE' }),
  },
  notifications: {
    list: () => request('/notifications/'),
    read: (id) => request(`/notifications/${id}/read`, { method: 'PUT' }),
    readAll: () => request('/notifications/read-all', { method: 'PUT' }),
    delete: (id) => request(`/notifications/${id}`, { method: 'DELETE' }),
  },
  email: {
    config: () => request('/email/config'),
    log: () => request('/email/log'),
    poll: () => request('/email/poll', { method: 'POST' }),
    stats: () => request('/email/stats'),
  },
};
