import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper';
import Login from 'pages/Login/LoginMain.vue';

describe('Login', () => {
    let vm;
    beforeAll(() => {
        vm = createWrapper(Login).vm;
    });

    afterEach(() => {
        vi.clearAllMocks();
    });

    it('should successfully set the token into session', async () => {
        const expectedUser = {
            id: 999,
            name: `T'Challa`,
            nickname: 'Black Panther',
            lang: 'en',
            userConfig: {
                darkMode: false,
            },
        };
        vi.spyOn(axios, 'post').mockResolvedValueOnce({ data: { token: 'token' } });
        vi.spyOn(axios, 'get').mockImplementation((url) => {
            if (url === 'VnUsers/acls') return Promise.resolve({ data: [] });
            return Promise.resolve({
                data: {
                    roles: [],
                    user: expectedUser,
                    multimediaToken: { id: 'multimediaToken' },
                },
            });
        });

        expect(vm.session.getToken()).toEqual('');

        await vm.onSubmit();

        expect(vm.session.getToken()).toEqual('token');
        await vm.session.destroy();
    });

    it('should not set the token into session if any error occurred', async () => {
        vi.spyOn(axios, 'post').mockReturnValue({ data: null });
        await vm.onSubmit();
    });
});
