"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IdentityHomePage = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("../../utils/sleep");
const expectLocatorWithRetry_1 = require("../../utils/assertionHelpers/expectLocatorWithRetry");
class IdentityHomePage {
    page;
    identityBanner;
    tasklistCell;
    operateCell;
    connectorsCell;
    accessToAPIsTab;
    assignPermissionsButton;
    dialog;
    addButton;
    permissionCell;
    select;
    constructor(page) {
        this.page = page;
        this.identityBanner = page.getByRole('link', {
            name: 'Camunda logo Identity',
        });
        this.accessToAPIsTab = page.getByRole('tab', { name: 'Access to APIs' });
        this.assignPermissionsButton = page.getByRole('button', {
            name: 'Assign permissions',
        });
        this.dialog = page.getByRole('dialog');
        this.addButton = page.getByRole('button', { name: 'Add' });
        this.permissionCell = (name) => page.getByRole('cell', { name: name });
        this.tasklistCell = this.permissionCell('Tasklist');
        this.operateCell = this.permissionCell('Operate');
        this.connectorsCell = this.permissionCell('Connectors');
        this.select = this.page.locator('select');
    }
    async selectAllCheckboxes(apiName) {
        const labels = this.dialog.locator('.cds--checkbox-label');
        try {
            await labels.first().waitFor({ state: 'visible', timeout: 30000 });
            for (const label of await labels.all()) {
                await label.click();
            }
            return true;
        }
        catch {
            console.log(`No checkboxes found for ${apiName}, skipping Add`);
            return false;
        }
    }
    async hasWritePermission() {
        return this.page
            .getByRole('cell')
            .filter({ hasText: /^write/ })
            .first()
            .isVisible()
            .catch(() => false);
    }
    // The Identity backend persists the assigned permission even when the Add
    // request returns a transient 404 and the dialog fails to close on its own.
    // The permission then shows up in the table after a short propagation delay,
    // so confirm against the table state (across reloads) rather than relying on
    // the dialog closing.
    async confirmWritePermissionAssigned() {
        for (let i = 0; i < 4; i++) {
            await this.dialog
                .waitFor({ state: 'hidden', timeout: 5000 })
                .catch(() => undefined);
            await this.page.reload();
            await (0, sleep_1.sleep)(2000);
            await this.accessToAPIsTab.click();
            await (0, sleep_1.sleep)(2000);
            if (await this.hasWritePermission()) {
                return true;
            }
        }
        return false;
    }
    async assignPermissions(appCell, apiName) {
        await (0, expectLocatorWithRetry_1.expectLocatorWithRetry)(this.page, appCell);
        await appCell.click();
        await this.accessToAPIsTab.click();
        await (0, sleep_1.sleep)(2000);
        for (let attempt = 1; attempt <= 3; attempt++) {
            if (await this.hasWritePermission()) {
                console.log(`Permissions already assigned to ${apiName}`);
                return;
            }
            await this.assignPermissionsButton.click();
            await this.selectOptionFromDropdown(apiName);
            await (0, test_1.expect)(this.dialog).toBeVisible();
            const checked = await this.selectAllCheckboxes(apiName);
            if (!checked) {
                return;
            }
            await (0, sleep_1.sleep)(1000);
            await (0, test_1.expect)(this.addButton).toBeVisible();
            await this.addButton.click();
            if (await this.confirmWritePermissionAssigned()) {
                console.log(`Permissions assigned to ${apiName}`);
                return;
            }
            console.log(`Add not confirmed for ${apiName} on attempt ${attempt}, retrying...`);
        }
        if (await this.hasWritePermission()) {
            return;
        }
        throw new Error(`Failed to assign permissions for ${apiName} after 3 attempts`);
    }
    async assignPermissionToTasklistAPI() {
        await this.assignPermissions(this.tasklistCell, 'Tasklist API');
    }
    async assignPermissionToOperateAPI() {
        await this.assignPermissions(this.operateCell, 'Operate API');
    }
    async selectOptionFromDropdown(option) {
        await this.select.selectOption({ label: option });
        await (0, sleep_1.sleep)(1000);
    }
}
exports.IdentityHomePage = IdentityHomePage;
