import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' const getAccessToken = vi.fn<() => string | null>(() => 'jwt-token') vi.mock('../../src/main/auth/session', () => ({ getAccessToken })) const { createSession, getSession, sendObjectiveMessage, confirmObjective, MaxApiError } = await import('../../src/main/api/sessionsClient') function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response { return { ok, status, json: () => Promise.resolve(body) } as Response } describe('sessionsClient', () => { const originalFetch = global.fetch beforeEach(() => { vi.clearAllMocks() getAccessToken.mockReturnValue('jwt-token') }) afterEach(() => { global.fetch = originalFetch }) it('should throw MaxApiError when there is no access token', async () => { getAccessToken.mockReturnValue(null) await expect(createSession()).rejects.toThrow(MaxApiError) }) it('should create a session with the bearer token', async () => { global.fetch = vi .fn() .mockResolvedValueOnce(jsonResponse({ id: 1, status: 'objective_discovery' })) const result = await createSession() expect(result).toEqual({ id: 1, status: 'objective_discovery' }) const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock .calls const call = calls.at(0) expect(call?.[0]).toContain('/sessions') expect((call?.[1]?.headers as Record)?.Authorization).toBe('Bearer jwt-token') }) it('should fetch a session by id', async () => { global.fetch = vi .fn() .mockResolvedValueOnce(jsonResponse({ id: 1, status: 'objective_discovery' })) await getSession(1) const calls = (global.fetch as unknown as { mock: { calls: [string][] } }).mock.calls expect(calls.at(0)?.[0]).toContain('/sessions/1') }) it('should send an objective message', async () => { global.fetch = vi .fn() .mockResolvedValueOnce(jsonResponse({ reply: 'Quel est ton sujet ?', ready: false })) const result = await sendObjectiveMessage(1, 'Je veux apprendre') expect(result.ready).toBe(false) const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock .calls const body = calls.at(0)?.[1]?.body as string expect(JSON.parse(body)).toEqual({ message: 'Je veux apprendre' }) }) it('should confirm the objective', async () => { global.fetch = vi.fn().mockResolvedValueOnce( jsonResponse({ id: 1, sessionId: 1, subject: 'x', professionalGoal: 'y', duration: '2 semaines', validatedAt: '2026-01-01T00:00:00.000Z' }) ) const result = await confirmObjective(1) expect(result.sessionId).toBe(1) }) it('should throw MaxApiError with the server message on a non-ok response', async () => { global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ message: 'Conflit' }, false, 409)) await expect(createSession()).rejects.toThrow('Conflit') }) it('should throw MaxApiError when the network call fails', async () => { global.fetch = vi.fn().mockRejectedValueOnce(new Error('ECONNREFUSED')) await expect(createSession()).rejects.toThrow(MaxApiError) }) })