// api.jsx — lightweight fetch client for the Psyche backend

function _apiToken() {
  try { return JSON.parse(localStorage.getItem('psyche-auth') || '{}').token || null; }
  catch { return null; }
}

function _apiHeaders() {
  const token = _apiToken();
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

async function _apiFetch(method, path, body) {
  const opts = { method, headers: _apiHeaders() };
  if (body !== undefined) opts.body = JSON.stringify(body);
  const r = await fetch('/api' + path, opts);
  let data;
  try { data = await r.json(); } catch { data = {}; }
  if (!r.ok) throw new Error(data.error || 'Request failed');
  return data;
}

const API = {
  // Auth
  login:  (d) => _apiFetch('POST', '/auth/login', d),
  signup: (d) => _apiFetch('POST', '/auth/signup', d),

  // Psychologist profiles
  getPsychologists:  ()    => _apiFetch('GET', '/psychologists'),
  getPsychologist:   (id)  => _apiFetch('GET', '/psychologists/' + id),
  getMyProfile:      ()    => _apiFetch('GET', '/psychologists/me'),
  saveMyProfile:     (d)   => _apiFetch('PUT', '/psychologists/me', d),
  saveAdminProfile:  (id, d) => _apiFetch('PUT', '/admin/psychologists/' + id, d),
  getAdminPsychologists: () => _apiFetch('GET', '/admin/psychologists'),
  getAdminAvailability:  (psyId) => _apiFetch('GET', '/admin/availability/' + psyId),
  resetAdminAvailability:(psyId, slots) => _apiFetch('POST', '/admin/availability/' + psyId + '/reset', { slots }),

  // Reviews
  getReviews:  (psyId) => _apiFetch('GET',  '/reviews/' + psyId),
  postReview:  (psyId, d) => _apiFetch('POST', '/reviews/' + psyId, d),

  // Community
  getCommunity:  () => _apiFetch('GET',  '/community'),
  postCommunity: (d) => _apiFetch('POST', '/community', d),

  // Bookings
  postBooking:        (d)  => _apiFetch('POST', '/bookings', d),
  getMyBookings:      ()   => _apiFetch('GET',  '/bookings/mine'),
  getIncomingBookings:  ()  => _apiFetch('GET',  '/bookings/incoming'),
  getUpcomingBookings:  ()  => _apiFetch('GET',  '/bookings/upcoming'),
  acceptBooking:      (id) => _apiFetch('POST', '/bookings/' + id + '/accept', {}),
  declineBooking:     (id, d) => _apiFetch('POST', '/bookings/' + id + '/decline', d),
  joinBooking:        (id) => _apiFetch('GET',  '/bookings/' + id + '/join'),

  // Availability (psychologist)
  getMyAvailability:  ()   => _apiFetch('GET', '/psychologists/me/availability'),
  saveMyAvailability: (slots) => _apiFetch('PUT', '/psychologists/me/availability', { slots }),

  // Public slots
  getSlots:         (psyId, date) => _apiFetch('GET', '/psychologists/' + psyId + '/slots?date=' + date),
  getAvailableDays: (psyId)       => _apiFetch('GET', '/psychologists/' + psyId + '/availability-days'),

  // Messaging
  getConversations: ()                      => _apiFetch('GET',  '/messages'),
  getUnreadCount:   ()                      => _apiFetch('GET',  '/messages/unread'),
  getThread:        (psyId, clientId)       => _apiFetch('GET',  '/messages/' + psyId + (clientId ? '?clientId=' + clientId : '')),
  sendMessage:      (psyId, body, clientId) => _apiFetch('POST', '/messages/' + psyId, { body, ...(clientId ? { clientUserId: clientId } : {}) }),
  markRead:         (psyId, clientId)       => _apiFetch('PUT',  '/messages/' + psyId + '/read', clientId ? { clientUserId: clientId } : {}),
};

Object.assign(window, { API });
