"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
 *  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *  SPDX-License-Identifier: Apache-2.0
 */
const workbench_core_base_1 = require("@aws/workbench-core-base");
const paabHelper_1 = require("../../../support/complex/paabHelper");
const HttpError_1 = __importDefault(require("../../../support/utils/HttpError"));
const utilities_1 = require("../../../support/utils/utilities");
describe('list environments', () => {
    const paabHelper = new paabHelper_1.PaabHelper(2);
    let itAdminSession;
    let paSession;
    let researcherSession;
    let rs1Session;
    let anonymousSession;
    let projectId1;
    let projectId2;
    const validEnvStatuses = [
        'PENDING',
        'COMPLETED',
        'STARTING',
        'STOPPING',
        'STOPPED',
        'TERMINATING',
        'TERMINATED',
        'FAILED',
        'TERMINATING_FAILED',
        'STARTING_FAILED',
        'STOPPING_FAILED'
    ];
    const invalidFilters = [
        {
            queryParams: { filter: { status: { eq: (0, utilities_1.generateRandomAlphaNumericString)(workbench_core_base_1.urlFilterMaxLength + 1) } } },
            message: `filter.status.eq: ${(0, workbench_core_base_1.lengthValidationMessage)(workbench_core_base_1.urlFilterMaxLength)}`
        },
        {
            queryParams: { filter: { name: { eq: (0, utilities_1.generateRandomAlphaNumericString)(workbench_core_base_1.urlFilterMaxLength + 1) } } },
            message: `filter.name.eq: ${(0, workbench_core_base_1.lengthValidationMessage)(workbench_core_base_1.urlFilterMaxLength)}`
        },
        {
            queryParams: {
                filter: { createdAt: { eq: (0, utilities_1.generateRandomAlphaNumericString)(workbench_core_base_1.urlFilterMaxLength + 1) } }
            },
            message: `filter.createdAt.eq: ${(0, workbench_core_base_1.lengthValidationMessage)(workbench_core_base_1.urlFilterMaxLength)}`
        },
        {
            queryParams: { filter: { owner: { eq: (0, utilities_1.generateRandomAlphaNumericString)(workbench_core_base_1.urlFilterMaxLength + 1) } } },
            message: `filter.owner.eq: ${(0, workbench_core_base_1.lengthValidationMessage)(workbench_core_base_1.urlFilterMaxLength)}`
        },
        {
            queryParams: {
                filter: { projectId: { eq: (0, utilities_1.generateRandomAlphaNumericString)(workbench_core_base_1.urlFilterMaxLength + 1) } }
            },
            message: `filter.projectId.eq: ${(0, workbench_core_base_1.lengthValidationMessage)(workbench_core_base_1.urlFilterMaxLength)}`
        }
    ];
    beforeEach(() => {
        expect.hasAssertions();
    });
    beforeAll(async () => {
        const paabResources = await paabHelper.createResources(__filename);
        itAdminSession = paabResources.adminSession;
        paSession = paabResources.pa1Session;
        researcherSession = paabResources.rs1Session;
        projectId1 = paabResources.project1Id;
        projectId2 = paabResources.project2Id;
        rs1Session = paabResources.rs1Session;
        anonymousSession = paabResources.anonymousSession;
    });
    afterAll(async () => {
        await paabHelper.cleanup();
    });
    describe('IT Admin tests', () => {
        test.each(invalidFilters)('list environments fails with invalid filter exceeding filter length', async (invalidFilter) => {
            try {
                await itAdminSession.resources.environments.get(invalidFilter.queryParams); //undefined values are not accepted by Json value
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(400, {
                    error: 'Bad Request',
                    message: invalidFilter.message
                }));
            }
        });
        test.each(validEnvStatuses)('list environments when status query is %s', async (status) => {
            const queryParams = {
                filter: { status: { eq: status } }
            };
            const { data: response } = await itAdminSession.resources.environments.get(queryParams);
            expect(Array.isArray(response.data)).toBe(true);
        });
        test('list environments with filter on empty name', async () => {
            try {
                await itAdminSession.resources.environments.get({ filter: { name: { eq: '' } } });
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(400, {
                    error: 'Bad Request',
                    message: `filter.name.eq: ${workbench_core_base_1.nonEmptyMessage}`
                }));
            }
        });
        test('list environments with filter createdAt between value1 > value2', async () => {
            try {
                await itAdminSession.resources.environments.get({
                    filter: {
                        createdAt: {
                            between: {
                                value1: '2023-05-14T07:23:39.311Z',
                                value2: '2023-05-11T07:23:39.311Z'
                            }
                        }
                    }
                });
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(400, {
                    error: 'Bad Request',
                    message: `filter.createdAt.between: ${workbench_core_base_1.betweenFilterMessage}`
                }));
            }
        });
        test('list project environments when project does not exist', async () => {
            const fakeProjectId = 'proj-12345678-1234-1234-1234-123456789012';
            try {
                await itAdminSession.resources.projects
                    .project(fakeProjectId)
                    .environments()
                    .listProjectEnvironments();
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(404, {
                    error: 'Not Found',
                    message: `Could not find project ${fakeProjectId}`
                }));
            }
        });
    });
    describe('Project Admin tests', () => {
        test('not authorized to call list environments', async () => {
            try {
                const queryParams = {
                    filter: { status: { eq: 'someInvalidStatus' } }
                };
                await paSession.resources.environments.get(queryParams);
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
        test('list project environments when project does not exist', async () => {
            const fakeProjectId = 'proj-12345678-1234-1234-1234-123456789012';
            try {
                await paSession.resources.projects.project(fakeProjectId).environments().listProjectEnvironments();
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
        test('list project environments when user not associated to a valid project', async () => {
            console.log('A Project Admin of Project1 and Project3, cannot LIST environments from Project2');
            try {
                await paSession.resources.projects.project(projectId2).environments().listProjectEnvironments();
                throw new Error('Listing project environments with unauthorized user did not throw an error');
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
    });
    describe('Researcher tests', () => {
        test('list project environments when user not associated to a valid project', async () => {
            console.log('A Researcher of Project1 and Project3, cannot LIST environments from Project2');
            try {
                await rs1Session.resources.projects.project(projectId2).environments().listProjectEnvironments();
                throw new Error('Listing project environments with unauthorized user did not throw an error');
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
        test('not authorized to call list environments', async () => {
            try {
                const queryParams = {
                    filter: { status: { eq: 'someInvalidStatus' } }
                };
                await researcherSession.resources.environments.get(queryParams);
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
        test('list project environments when project does not exist', async () => {
            const fakeProjectId = 'proj-12345678-1234-1234-1234-123456789012';
            try {
                await researcherSession.resources.projects
                    .project(fakeProjectId)
                    .environments()
                    .listProjectEnvironments();
            }
            catch (e) {
                (0, utilities_1.checkHttpError)(e, new HttpError_1.default(403, {
                    error: 'User is not authorized'
                }));
            }
        });
    });
    describe('with invalid paginationToken', () => {
        const pagToken = '1';
        const queryParams = { paginationToken: pagToken };
        describe('as IT Admin', () => {
            test('it throws 400 error', async () => {
                try {
                    await itAdminSession.resources.environments.get(queryParams);
                }
                catch (e) {
                    (0, utilities_1.checkHttpError)(e, new HttpError_1.default(400, {
                        error: 'Bad Request',
                        message: `Invalid Pagination Token: ${queryParams.paginationToken}`
                    }));
                }
            });
        });
        // PA & Researcher must be project environment route
        const testBundle = [
            {
                username: 'projectAdmin',
                session: () => paSession,
                projectId: () => projectId1
            },
            {
                username: 'researcher',
                session: () => researcherSession,
                projectId: () => projectId1
            }
        ];
        describe.each(testBundle)('for each user', (testCase) => {
            const { username, session: sessionFunc, projectId: projectFunc } = testCase;
            let session;
            let projectId;
            beforeEach(async () => {
                session = sessionFunc();
                projectId = projectFunc();
            });
            test(`it throws 400 error as ${username}`, async () => {
                try {
                    await session.resources.projects
                        .project(projectId)
                        .environments()
                        .listProjectEnvironments(queryParams);
                }
                catch (e) {
                    (0, utilities_1.checkHttpError)(e, new HttpError_1.default(400, {
                        error: 'Bad Request',
                        message: `Invalid Pagination Token: ${queryParams.paginationToken}`
                    }));
                }
            });
        });
    });
    test('Unauthenticated user not authorized to call list environments', async () => {
        try {
            await anonymousSession.resources.environments.get({});
        }
        catch (e) {
            (0, utilities_1.checkHttpError)(e, new HttpError_1.default(401, {}));
        }
    });
});
//# sourceMappingURL=list.test.js.map