const API = {
  async request(path, options = {}) {
    const res = await fetch(path, {
      credentials: 'include',
      headers: { 'Content-Type': 'application/json', ...options.headers },
      ...options,
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      const detail = data.detail;
      const msg = Array.isArray(detail)
        ? detail.map((d) => d.msg).join(', ')
        : detail || 'Ошибка запроса';
      throw new Error(msg);
    }
    return data;
  },
  me: () => API.request('/api/auth/me'),
  logout: () => API.request('/api/auth/logout', { method: 'POST' }),
  getProfile: () => API.request('/api/profile'),
  updateProfile: (body) => API.request('/api/profile', { method: 'PUT', body: JSON.stringify(body) }),
  getRobots: () => API.request('/api/robots'),
  saveRobots: (body) => API.request('/api/robots', { method: 'PUT', body: JSON.stringify(body) }),
  getSessions: () => API.request('/api/sessions'),
};
