// Typed fetch helpers. Every call sends credentials so the cross-origin session cookie is included.

const WORKER_URL = 'https://snatch-coach.henryfan1104.workers.dev';

async function apiFetch(path, { method = 'GET', body } = {}) {
  const init = {
    method,
    credentials: 'include',
    headers: {},
  };
  if (body !== undefined) {
    init.headers['Content-Type'] = 'application/json';
    init.body = JSON.stringify(body);
  }
  const res = await fetch(WORKER_URL + path, init);
  const ct = res.headers.get('Content-Type') || '';
  const data = ct.includes('application/json') ? await res.json().catch(() => ({})) : {};
  if (!res.ok) {
    const err = new Error(data.error || `HTTP ${res.status}`);
    err.status = res.status;
    err.payload = data;
    throw err;
  }
  return data;
}

const API = {
  workerUrl: WORKER_URL,
  googleLoginUrl: (returnTo = window.location.href) => {
    const url = new URL(WORKER_URL + '/api/auth/google/start');
    if (returnTo) url.searchParams.set('return_to', returnTo);
    return url.toString();
  },

  me: () => apiFetch('/api/auth/me'),
  logout: () => apiFetch('/api/auth/logout', { method: 'POST', body: {} }),

  listWods: () => apiFetch('/api/wods'),
  saveWod: (wod) => apiFetch('/api/wods', { method: 'POST', body: { wod } }),
  deleteWod: (id) => apiFetch('/api/wods/' + encodeURIComponent(id), { method: 'DELETE' }),

  listChats: () => apiFetch('/api/chats'),
  createChat: () => apiFetch('/api/chats', { method: 'POST', body: {} }),
  getChat: (id) => apiFetch('/api/chats/' + encodeURIComponent(id)),
  renameChat: (id, title) => apiFetch('/api/chats/' + encodeURIComponent(id), { method: 'PATCH', body: { title } }),
  deleteChat: (id) => apiFetch('/api/chats/' + encodeURIComponent(id), { method: 'DELETE' }),
  chatTurn: (id, content) => apiFetch('/api/chats/' + encodeURIComponent(id) + '/turn', { method: 'POST', body: { content } }),
};

window.SnatchAPI = API;
