import { describe, test, expect, vi, beforeEach } from 'vitest';
import { Client } from '@vulog/aima-client';
import { getUserByEmail } from './getUserByEmail';

describe('getUserByEmail', () => {
    const FLEET_ID = 'FLEET_ID';
    const getMock = vi.fn();
    const client = {
        get: getMock,
        clientOptions: {
            fleetId: FLEET_ID,
        },
    } as unknown as Client;

    beforeEach(() => {
        getMock.mockReset();
    });

    test('throws Invalid args when email is invalid', async () => {
        await expect(getUserByEmail(client, 'not-an-email')).rejects.toThrow(TypeError);
        await expect(getUserByEmail(client, 'not-an-email')).rejects.toMatchObject({
            message: 'Invalid args',
        });
        expect(getMock).not.toHaveBeenCalled();
    });

    test('throws Invalid args when email is empty', async () => {
        await expect(getUserByEmail(client, '')).rejects.toThrow(TypeError);
        expect(getMock).not.toHaveBeenCalled();
    });

    test('calls GET with correct URL (email encoded) and returns user', async () => {
        const email = 'user+tag@example.com';
        const userData = {
            id: '20fb98a3-b60d-491a-9359-62e55f51fcb9',
            fleetId: FLEET_ID,
            registrationDate: '2024-01-15T10:00:00Z',
            locale: 'en_GB',
            agreements: [],
            profiles: [],
            dataPrivacyConsent: true,
            marketingConsent: false,
            surveyConsent: false,
            shareDataConsent: false,
            surveyConsentUpdateDate: '',
            shareDataConsentUpdateDate: '',
            profilingConsent: false,
            profilingConsentUpdateDate: '',
        };
        getMock.mockResolvedValueOnce({ data: userData });

        const result = await getUserByEmail(client, email);

        expect(getMock).toHaveBeenCalledTimes(1);
        expect(getMock).toHaveBeenCalledWith(
            `/boapi/proxy/user/fleets/${FLEET_ID}/usernames/${encodeURIComponent(email)}`
        );
        expect(result).toEqual(userData);
        expect(result.id).toBe(userData.id);
    });
});
