import { getAccessToken } from '../auth/session' import type { ObjectiveMessageResponse, SessionObjectiveResponse, SessionResponse } from '../../shared/session' export class MaxApiError extends Error { constructor( message: string, public readonly statusCode?: number ) { super(message) this.name = 'MaxApiError' } } function getMaxApiUrl(): string { return process.env.MAX_API_URL || 'http://localhost:3000' } async function call(path: string, init: RequestInit = {}): Promise { const token = getAccessToken() if (!token) throw new MaxApiError("Aucun jeton de session : connecte-toi d'abord") let response: Response try { response = await fetch(`${getMaxApiUrl()}${path}`, { ...init, headers: { ...init.headers, Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } }) } catch (error) { throw new MaxApiError( `Max API injoignable: ${error instanceof Error ? error.message : String(error)}` ) } if (!response.ok) { const body = (await response.json().catch(() => null)) as { message?: string } | null throw new MaxApiError(body?.message ?? `Max API a renvoye ${response.status}`, response.status) } return (await response.json()) as T } export function createSession(): Promise { return call('/sessions', { method: 'POST' }) } export function getSession(id: number): Promise { return call(`/sessions/${id}`) } export function sendObjectiveMessage( id: number, message: string ): Promise { return call(`/sessions/${id}/objective/message`, { method: 'POST', body: JSON.stringify({ message } satisfies { message: string }) }) } export function confirmObjective(id: number): Promise { return call(`/sessions/${id}/objective/confirm`, { method: 'POST' }) }