import axios from 'axios';
import globalMethods from '@/global-methods';
import analyticsMixIn from '@/mixins/analytics-mixin';
import { getMountOptions } from '@/helpers/unit-test-helper.js';
import crypto from 'crypto';

// Mock external dependencies
jest.mock('axios');
jest.mock('@/mixins/analytics-mixin');

global.crypto = crypto;

global.$logger = {
    logInformation: jest.fn(),
    logWarning: jest.fn(),
    logError: jest.fn(),
    logCritical: jest.fn()
};

/** @ignore */
function setupMocksForHttpClient({
    endpoint = null,
    isError = false,
    additionalData = null
}) {
    // Clear node module
    axios.mockClear();

    getMountOptions();

    // Success Response
    const response = {
        status: 200,
        data: {
            message: 'Success',
            additionalData
        }
    };

    // Error Response
    const error = {
        response: {
            status: 500,
            data: {
                message: 'Error',
                additionalData
            }
        }
    };

    // Error interceptor on Axios returns a different object, so we need to mimic that.
    if (isError) {
        axios.mockRejectedValue(error);
    } else {
        axios.mockResolvedValue(response);
    }

    return {
        endpoint,
        logApiCall: true
    };
}

it('Global Methods - Call Http Client - Should Resolve Promise', () => {
    // Arrange
    const endpoint = 'https://mock.safelite.com';
    const httpArgs = setupMocksForHttpClient({ endpoint });

    // Act
    globalMethods.callHttpClient(httpArgs).then((response) => {
        // Assert
        expect(axios.mock.calls[0][0].url).toContain(endpoint);
        expect(response.data.message).toContain('Success');
        expect(response.status).toEqual(200);
    });
});

it('Global Methods - Call Http Client - Should Reject Promise', () => {
    // Arrange
    const endpoint = 'https://mock.safelite.com';
    const httpArgs = setupMocksForHttpClient({
        endpoint,
        isError: true
    });
    analyticsMixIn.methods.pushEventToGA = jest.fn();

    // Act
    globalMethods.callHttpClient(httpArgs).catch((err) => {
        // Assert
        expect(axios.mock.calls[0][0].url).toContain(endpoint);
        expect(err.data.message).toContain('Error');
        expect(err.status).toEqual(500);
    });
});
