/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { render } from '@testing-library/react';
import * as ReactQuery from 'react-query';
import { BrowserRouter } from 'react-router-dom';
import React from 'react';
import { UseMutationResult, UseQueryResult } from 'react-query';
import {
    fixtureCreatePatternFormValues,
    fixtureUpdatePatternFormValues,
    patternUpdateFormNavigateAndAssert,
} from '../../../containers/Patterns/Form/index.test';
import PatternUpdate from '.';
import getAllAttributesQuery from '../../../queries/GetAllAttributesQuery';

// Mocks
const mockMutateFn = jest.fn();
const mockUseHistoryReplaceFn = jest.fn();
const mockUseHistoryPushFn = jest.fn();
const mockAddNotificationFn = jest.fn();

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useHistory: () => ({
        push: mockUseHistoryPushFn,
        replace: mockUseHistoryReplaceFn,
    }),
    useParams: () => ({
        blueprintId: fixtureGetPatternDetails.metadata.patternId,
    }),
}));

jest.mock('aws-northstar/layouts/AppLayout', () => ({
    ...jest.requireActual('aws-northstar/layouts/AppLayout'),
    useAppLayoutContext: () => ({
        addNotification: mockAddNotificationFn,
    }),
}));

jest.mock('react-query', () => ({
    ...jest.requireActual('react-query'),
    useQuery: jest.fn(),
    useMutation: jest.fn(),
}));

const mockReactQuery = ReactQuery as jest.Mocked<typeof ReactQuery>;

const fixtureListAttributesData = {
    results: [
        {
            name: 'testAttribute:testAttrValue',
            description: 'testAttribute',
            key: 'testAttribute',
            value: 'testAttrValue',
            metadata: {
                key1: 'value1',
            },
            createTime: '2021-11-17T06:02:52.748Z',
            lastUpdateTime: '2021-11-17T06:02:52.748Z',
        },
        {
            name: 'testAttribute2:testAttrValue2',
            description: 'testAttribute2',
            key: 'testAttribute2',
            value: 'testAttrValue2',
            metadata: {
                key1: 'value1',
            },
            createTime: '2021-11-17T06:02:52.748Z',
            lastUpdateTime: '2021-11-17T06:02:52.748Z',
        },
    ],
};

const fixtureGetPatternDetails = {
    metadata: {
        codeRepository: {
            branchName: 'master',
            type: 'github',
            repoOwner: 'test-enterprise',
            repoName: 'test-repo',
        },
        updatedTimestamp: '2022-10-11T05:49:01.275Z',
        attributes: {
            testAttribute: 'testAttrValue',
            testAttribute2: 'testAttrValue2',
        },
        patternType: 'CDK',
        description: 'test pattern description',
        createdTimestamp: '2022-10-11T05:29:29.739Z',
        name: 'test-pattern-1',
        patternRepoURL: 'git://dev.github-enterprise.xyz/enterprise/test-pattern-1.git',
        infrastructureStackStatus: 'CREATE_COMPLETE',
        patternId: 'test-pattern-1',
    },
};

describe('PatternUpdate', () => {
    let useMutationOptions: any;

    beforeEach(() => {
        mockAddNotificationFn.mockRestore();
        mockMutateFn.mockRestore();
        mockUseHistoryReplaceFn.mockRestore();
    });

    beforeEach(() => {
        mockReactQuery.useMutation.mockImplementation(
            (_mutationFn: any, options?: any) => {
                useMutationOptions = options;

                return {
                    isLoading: false,
                    mutate: mockMutateFn,
                } as unknown as UseMutationResult;
            }
        );
    });

    test('render update on success', async () => {
        mockMutateFn.mockImplementation((_request: any) => {
            useMutationOptions.onSuccess(null, fixtureCreatePatternFormValues);
        });
        mockReactQuery.useQuery
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureGetPatternDetails,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureListAttributesData,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureGetPatternDetails,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureListAttributesData,
            } as UseQueryResult);

        const renderResult = render(
            <BrowserRouter>
                <PatternUpdate />
            </BrowserRouter>
        );

        await patternUpdateFormNavigateAndAssert(renderResult);

        expect(mockReactQuery.useQuery).toBeCalledWith(
            'listAttributes',
            getAllAttributesQuery,
            expect.anything()
        );

        expect(mockMutateFn).toHaveBeenCalledWith({
            description: fixtureCreatePatternFormValues.description,
            attributes: Object.fromEntries(
                fixtureCreatePatternFormValues.attributes.map((item) => [
                    item.key,
                    item.value,
                ])
            ),
            patternId: fixtureGetPatternDetails.metadata.patternId,
        });
    });

    test('render update on error', async () => {
        mockReactQuery.useQuery
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureGetPatternDetails,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureListAttributesData,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureGetPatternDetails,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureListAttributesData,
            } as UseQueryResult);

        mockMutateFn.mockImplementation((_request: any) => {
            useMutationOptions.onError(
                { message: 'test error message' },
                fixtureUpdatePatternFormValues
            );
        });

        const renderResult = render(
            <BrowserRouter>
                <PatternUpdate />
            </BrowserRouter>
        );

        await patternUpdateFormNavigateAndAssert(renderResult);

        expect(mockAddNotificationFn).toHaveBeenCalledWith({
            header: `Failed to update the pattern ${fixtureCreatePatternFormValues.name}`,
            id: expect.anything(),
            type: 'error',
            dismissible: true,
            content: 'test error message',
        });
    });

    test('render the loading errors - attributes', () => {
        const errorMsg = 'Unable to load attributes';

        mockReactQuery.useQuery
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureGetPatternDetails,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: true,
                data: undefined,
                error: errorMsg,
            } as UseQueryResult);

        const { getByText } = render(
            <BrowserRouter>
                <PatternUpdate />
            </BrowserRouter>
        );
        expect(getByText(errorMsg)).toBeInTheDocument();
    });

    test('render the loading errors - pattern metadata', () => {
        const errorMsg = 'Unable to load pattern metadata';

        mockReactQuery.useQuery
            .mockReturnValueOnce({
                isLoading: false,
                isError: true,
                data: undefined,
                error: errorMsg,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: false,
                isError: false,
                data: fixtureListAttributesData,
            } as UseQueryResult);

        const { getByText } = render(
            <BrowserRouter>
                <PatternUpdate />
            </BrowserRouter>
        );
        expect(getByText(errorMsg)).toBeInTheDocument();
    });

    test('render the loading in progress', () => {
        mockReactQuery.useQuery
            .mockReturnValueOnce({
                isLoading: true,
                data: undefined,
            } as UseQueryResult)
            .mockReturnValueOnce({
                isLoading: true,
                data: undefined,
            } as UseQueryResult);

        const { getByRole } = render(
            <BrowserRouter>
                <PatternUpdate />
            </BrowserRouter>
        );
        expect(getByRole('progressbar')).toBeInTheDocument();
    });
});
