"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const test_1 = require("@playwright/test");
const _8_10_1 = require("../../fixtures/8.10");
const apiHelpers_1 = require("../../utils/apiHelpers");
const randomName_1 = require("../../utils/randomName");
_8_10_1.test.describe.configure({ mode: 'parallel' });
const DEFINITION_KEY = 'customer_onboarding_en';
const expectUnauthorizedErrorBody = (body) => {
    if (body === null || body === undefined)
        return;
    if (typeof body === 'string') {
        return;
    }
    (0, test_1.expect)(typeof body).toBe('object');
    const errorBody = body;
    const errorMessage = errorBody.message ?? errorBody.error ?? errorBody.title ?? errorBody.detail;
    (0, test_1.expect)(typeof errorMessage).toBe('string');
    (0, test_1.expect)(errorMessage.trim().length).toBeGreaterThan(0);
};
const assertUnauthorizedResponseBody = async (response) => {
    (0, test_1.expect)(response.status()).toBe(401);
    const rawBody = await response.text();
    if (rawBody.trim().length === 0)
        return;
    let body = rawBody;
    try {
        body = JSON.parse(rawBody);
    }
    catch {
        body = rawBody;
    }
    expectUnauthorizedErrorBody(body);
};
const createNumberReport = async (request, options) => {
    const response = await request.post(`${options.baseUrl}/api/report/process/single`, {
        headers: {
            Cookie: options.optimizeCookie,
            'Content-Type': 'application/json',
        },
        data: {
            collectionId: options.collectionId,
            name: options.name,
            description: null,
            data: {
                definitions: [
                    {
                        key: DEFINITION_KEY,
                        versions: ['all'],
                        tenantIds: ['<default>'],
                    },
                ],
                view: { entity: 'processInstance', properties: ['frequency'] },
                groupBy: { type: 'none', value: null },
                distributedBy: { type: 'none', value: null },
                visualization: 'number',
                filter: [],
            },
        },
    });
    await (0, apiHelpers_1.assertResponseStatus)(response, 200);
    const body = await response.json();
    (0, test_1.expect)(body).toHaveProperty('id');
    return body.id;
};
const createRawDataReport = async (request, options) => {
    const response = await request.post(`${options.baseUrl}/api/report/process/single`, {
        headers: {
            Cookie: options.optimizeCookie,
            'Content-Type': 'application/json',
        },
        data: {
            collectionId: options.collectionId,
            name: options.name,
            description: null,
            data: {
                definitions: [
                    {
                        key: DEFINITION_KEY,
                        versions: ['all'],
                        tenantIds: ['<default>'],
                    },
                ],
                view: { entity: null, properties: ['rawData'] },
                groupBy: { type: 'none', value: null },
                distributedBy: { type: 'none', value: null },
                visualization: 'table',
                filter: [],
            },
        },
    });
    await (0, apiHelpers_1.assertResponseStatus)(response, 200);
    const body = await response.json();
    (0, test_1.expect)(body).toHaveProperty('id');
    return body.id;
};
_8_10_1.test.describe('API Optimize Sharing, Alerts & Export Tests @optimize-sharing-alerts-export-api @8.10', () => {
    let optimizeCookie;
    let optimizeBearerToken;
    let baseUrl;
    let collectionId;
    let numberReportId;
    let rawDataReportId;
    let dashboardId;
    _8_10_1.test.beforeAll(async ({ browser, request }) => {
        const page = await browser.newPage();
        optimizeCookie = await (0, apiHelpers_1.getOptimizeCoockie)(page);
        await page.close();
        optimizeBearerToken = await (0, apiHelpers_1.authSaasAPI)(process.env.OPTIMIZE_API_TOKEN_AUDIENCE);
        baseUrl = process.env.CAMUNDA_OPTIMIZE_BASE_URL;
        collectionId = await (0, apiHelpers_1.createCollection)(request, {
            name: await (0, randomName_1.randomNameAgregator)('Sharing Alerts Collection'),
            optimizeCookie,
        });
        await (0, apiHelpers_1.updateCollectionScope)(request, {
            optimizeCookie,
            collectionId,
            data: [
                {
                    definitionKey: DEFINITION_KEY,
                    definitionType: 'process',
                    tenants: ['<default>'],
                },
            ],
        });
        numberReportId = await createNumberReport(request, {
            baseUrl,
            optimizeCookie,
            collectionId,
            name: await (0, randomName_1.randomNameAgregator)('Number Report'),
        });
        rawDataReportId = await createRawDataReport(request, {
            baseUrl,
            optimizeCookie,
            collectionId,
            name: await (0, randomName_1.randomNameAgregator)('Raw Data Report'),
        });
        dashboardId = await (0, apiHelpers_1.createDashboard)(request, {
            name: await (0, randomName_1.randomNameAgregator)('Sharing Dashboard'),
            optimizeCookie,
            collectionId,
        });
    });
    _8_10_1.test.afterAll(async ({ request }) => {
        if (collectionId) {
            await request.delete(`${baseUrl}/api/public/collection/${collectionId}`, {
                headers: { Authorization: optimizeBearerToken },
            });
        }
    });
    (0, _8_10_1.test)('Export report result data returns 200 with paginated payload', async ({ request, }) => {
        await _8_10_1.test.step('GET /api/public/export/report/{id}/result/json (200)', async () => {
            const response = await request.get(`${baseUrl}/api/public/export/report/${rawDataReportId}/result/json?paginationTimeout=60&limit=100`, { headers: { Authorization: optimizeBearerToken } });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(body).toHaveProperty('reportId', rawDataReportId);
            (0, test_1.expect)(body).toHaveProperty('totalNumberOfRecords');
            (0, test_1.expect)(typeof body.totalNumberOfRecords).toBe('number');
            (0, test_1.expect)(body).toHaveProperty('data');
            (0, test_1.expect)(Array.isArray(body.data)).toBeTruthy();
        });
    });
    (0, _8_10_1.test)('Export report result data without pagination params returns 200', async ({ request, }) => {
        await _8_10_1.test.step('GET export result with optional query params omitted (200)', async () => {
            const response = await request.get(`${baseUrl}/api/public/export/report/${numberReportId}/result/json`, { headers: { Authorization: optimizeBearerToken } });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(body).toHaveProperty('reportId', numberReportId);
        });
    });
    (0, _8_10_1.test)('Export report result data without token returns 401', async ({ request, }) => {
        await _8_10_1.test.step('GET export result without Authorization header (401)', async () => {
            const response = await request.get(`${baseUrl}/api/public/export/report/${numberReportId}/result/json?paginationTimeout=60&limit=100`);
            await assertUnauthorizedResponseBody(response);
        });
    });
    (0, _8_10_1.test)('Export report result data with invalid token returns 401', async ({ request, }) => {
        await _8_10_1.test.step('GET export result with invalid token (401)', async () => {
            const response = await request.get(`${baseUrl}/api/public/export/report/${numberReportId}/result/json?paginationTimeout=60&limit=100`, { headers: { Authorization: 'Bearer invalid_token' } });
            await assertUnauthorizedResponseBody(response);
        });
    });
    (0, _8_10_1.test)('Export result data for non-existent report is rejected (404; SaaS may respond 500)', async ({ request, }) => {
        await _8_10_1.test.step('GET export result for missing report (404 or 500)', async () => {
            const response = await request.get(`${baseUrl}/api/public/export/report/11111111-1111-1111-1111-111111111111/result/json?paginationTimeout=60&limit=100`, { headers: { Authorization: optimizeBearerToken } });
            (0, test_1.expect)([404, 500]).toContain(response.status());
        });
    });
    (0, _8_10_1.test)('Enable, evaluate and delete a report share', async ({ request }) => {
        let reportShareId = '';
        await _8_10_1.test.step('POST /api/share/report enables sharing (200)', async () => {
            const response = await request.post(`${baseUrl}/api/share/report`, {
                headers: {
                    Cookie: optimizeCookie,
                    'Content-Type': 'application/json',
                },
                data: { reportId: numberReportId },
            });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(body).toHaveProperty('id');
            reportShareId = body.id;
            (0, test_1.expect)(reportShareId.length).toBeGreaterThan(0);
        });
        await _8_10_1.test.step('Shared report is evaluable without authentication', async () => {
            const response = await request.post(`${baseUrl}/api/external/share/report/${reportShareId}/evaluate`, {
                headers: { 'Content-Type': 'application/json' },
                data: {},
            });
            (0, test_1.expect)([200, 201]).toContain(response.status());
        });
        await _8_10_1.test.step('DELETE /api/share/report/{shareId} removes the share', async () => {
            const response = await request.delete(`${baseUrl}/api/share/report/${reportShareId}`, { headers: { Cookie: optimizeCookie } });
            (0, test_1.expect)([200, 204]).toContain(response.status());
        });
    });
    (0, _8_10_1.test)('Enable report share without auth cookie returns 401', async ({ request, }) => {
        await _8_10_1.test.step('POST /api/share/report without cookie (401)', async () => {
            const response = await request.post(`${baseUrl}/api/share/report`, {
                headers: { 'Content-Type': 'application/json' },
                data: { reportId: numberReportId },
            });
            await assertUnauthorizedResponseBody(response);
        });
    });
    (0, _8_10_1.test)('Enable and delete a dashboard share', async ({ request }) => {
        let dashboardShareId = '';
        await _8_10_1.test.step('POST /api/share/dashboard enables sharing (200)', async () => {
            const response = await request.post(`${baseUrl}/api/share/dashboard`, {
                headers: {
                    Cookie: optimizeCookie,
                    'Content-Type': 'application/json',
                },
                data: { dashboardId },
            });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(body).toHaveProperty('id');
            dashboardShareId = body.id;
            (0, test_1.expect)(dashboardShareId.length).toBeGreaterThan(0);
        });
        await _8_10_1.test.step('DELETE /api/share/dashboard/{shareId} removes the share', async () => {
            const response = await request.delete(`${baseUrl}/api/share/dashboard/${dashboardShareId}`, { headers: { Cookie: optimizeCookie } });
            (0, test_1.expect)([200, 204]).toContain(response.status());
        });
    });
    (0, _8_10_1.test)('Create, list and delete an alert for a number report', async ({ request, }) => {
        let alertId = '';
        const alertEmail = process.env.C8_USERNAME;
        await _8_10_1.test.step('POST /api/alert creates an alert (200)', async () => {
            const response = await request.post(`${baseUrl}/api/alert`, {
                headers: {
                    Cookie: optimizeCookie,
                    'Content-Type': 'application/json',
                },
                data: {
                    name: await (0, randomName_1.randomNameAgregator)('Number Report Alert'),
                    reportId: numberReportId,
                    emails: [alertEmail],
                    webhook: null,
                    threshold: 100,
                    thresholdOperator: '>',
                    fixNotification: false,
                    checkInterval: { value: 10, unit: 'minutes' },
                    reminder: null,
                },
            });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(body).toHaveProperty('id');
            alertId = body.id;
            (0, test_1.expect)(alertId.length).toBeGreaterThan(0);
        });
        await _8_10_1.test.step('GET /api/collection/{id}/alerts includes the created alert', async () => {
            const response = await request.get(`${baseUrl}/api/collection/${collectionId}/alerts`, { headers: { Cookie: optimizeCookie } });
            await (0, apiHelpers_1.assertResponseStatus)(response, 200);
            const body = await response.json();
            (0, test_1.expect)(Array.isArray(body)).toBeTruthy();
            const ids = body.map((alert) => alert.id);
            (0, test_1.expect)(ids).toContain(alertId);
        });
        await _8_10_1.test.step('DELETE /api/alert/{id} removes the alert', async () => {
            const response = await request.delete(`${baseUrl}/api/alert/${alertId}`, {
                headers: { Cookie: optimizeCookie },
            });
            (0, test_1.expect)([200, 204]).toContain(response.status());
        });
    });
    (0, _8_10_1.test)('Create alert without auth cookie returns 401', async ({ request }) => {
        await _8_10_1.test.step('POST /api/alert without cookie (401)', async () => {
            const response = await request.post(`${baseUrl}/api/alert`, {
                headers: { 'Content-Type': 'application/json' },
                data: {
                    name: await (0, randomName_1.randomNameAgregator)('Unauthorized Alert'),
                    reportId: numberReportId,
                    emails: [process.env.C8_USERNAME],
                    threshold: 100,
                    thresholdOperator: '>',
                    checkInterval: { value: 10, unit: 'minutes' },
                },
            });
            await assertUnauthorizedResponseBody(response);
        });
    });
});
