import type { ConnectPayment, ConnectPaymentResult, CreateFirstGroup, CreateFirstGroupResult, GroupList, OnboardingStatusDto, ProblemDetails, } from '@gruperly/shared' const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000' export class ApiError extends Error { constructor( readonly status: number, readonly problem: ProblemDetails | null, ) { super(problem?.title ?? `Error ${status}`) this.name = 'ApiError' } } type JsonBody = Record | unknown[] async function apiFetch(path: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers) headers.set('Content-Type', 'application/json') const res = await fetch(`${API_URL}${path}`, { ...init, headers, credentials: 'include', }) if (!res.ok) { let problem: ProblemDetails | null = null try { const body = (await res.json()) as Partial if (body && typeof body === 'object' && typeof body.title === 'string') { problem = body as ProblemDetails } } catch { // Sin cuerpo JSON: usamos el error genérico. } throw new ApiError(res.status, problem) } return (await res.json()) as T } export const getOnboardingStatus = () => apiFetch('/api/v1/onboarding/status') export const connectPayment = (payload: ConnectPayment) => apiFetch('/api/v1/onboarding/payment-setup', { method: 'POST', body: JSON.stringify(payload), }) export const createFirstGroup = (payload: CreateFirstGroup) => apiFetch('/api/v1/onboarding/first-group', { method: 'POST', body: JSON.stringify(payload), }) export const getGroups = () => apiFetch('/api/v1/groups')