import { describe, it, expect, vi, beforeEach } from 'vitest';
import logout from './logout';

vi.mock('../getXSRF.js', () => {
    return {
        default: vi.fn(() => Promise.resolve('fake-csrf-token'))
    };
});

describe('logout()', () => {

    beforeEach(() => {
        vi.clearAllMocks();
        global.fetch = vi.fn();
    });

    it('envoie bien la requête de logout', async () => {
        global.fetch.mockResolvedValue({
            ok: true,
            status: 200
        });

        const result = await logout();

        expect(global.fetch).toHaveBeenCalledOnce();
        expect(global.fetch).toHaveBeenCalledWith(
            `http://${import.meta.env.VITE_API_URL}/api/users/logout`,
            {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-XSRF-TOKEN': 'fake-csrf-token'
                },
            }
        );

        expect(result).toEqual({ status: 200 });
    });

    it('renvoie une erreur quand la réponse HTTP est mauvaise', async () => {
        global.fetch.mockResolvedValue({
            ok: false,
            status: 500
        });

        const result = await logout();

        expect(result).toBeInstanceOf(Error);
        expect(result.message).toBe('Erreur HTTP 500');
    });
});
