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

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

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

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

    it('envoie la requête de login et retourne les données utilisateur', async () => {
        global.fetch.mockResolvedValue({
            ok: true,
            status: 200,
            json: async () => ({ id: 1, name: 'John Doe' })
        });

        const result = await login('test@example.com', 'secret');

        expect(global.fetch).toHaveBeenCalledOnce();
        expect(global.fetch).toHaveBeenCalledWith(
            `http://${import.meta.env.VITE_API_URL}/api/users/login`,
            {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': 'fake-csrf-token',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ email: 'test@example.com', password: 'secret' })
            }
        );

        expect(result).toEqual({
            status: 200,
            data: { id: 1, name: 'John Doe' }
        });
    });

    it('retourne un objet avec status et erreurs quand la réponse HTTP est mauvaise', async () => {
        global.fetch.mockResolvedValue({
            ok: false,
            status: 401,
            json: async () => ({ message: 'Unauthorized' })
        });

        const result = await login('x', 'y');

        expect(result).toEqual({
            status: 401,
            errors: 'Unauthorized'
        });
    });

    it('retourne un objet avec status 500 en cas d’exception', async () => {
        global.fetch.mockImplementation(() => { throw new Error('Network Error') });

        const result = await login('x', 'y');

        expect(result.status).toBe(500);
        expect(result.error).toBeInstanceOf(Error);
        expect(result.error.message).toBe('Network Error');
    });
});
