"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NavigationPage = void 0;
const test_1 = require("@playwright/test");
const LoginPage_1 = require("./LoginPage");
const sleep_1 = require("../../utils/sleep");
const constants_1 = require("../../utils/constants");
const KeycloakUtils_1 = require("../SM-8.7/KeycloakUtils");
class NavigationPage {
    page;
    modelerPageBanner;
    operatePageBanner;
    tasklistPageBanner;
    optimizePageBanner;
    identityPageBanner;
    consolePageBanner;
    keyboardPageBanner;
    activeUser;
    activePassword;
    user1;
    user2;
    user1password;
    user2password;
    constructor(page) {
        this.page = page;
        this.activeUser = process.env.IS_MIGRATION === 'true' ? KeycloakUtils_1.adminUser : '';
        this.activePassword =
            process.env.IS_MIGRATION === 'true' ? KeycloakUtils_1.adminPassword : '';
        this.user1 = '';
        this.user2 = '';
        this.user1password = '';
        this.user2password = '';
        this.operatePageBanner = page.getByRole('link', {
            name: 'Camunda logo Operate',
        });
        this.modelerPageBanner = page
            .locator('a')
            .filter({ hasText: 'Camunda logoModeler' });
        this.tasklistPageBanner = page.getByRole('link', {
            name: 'Camunda logo Tasklist',
        });
        this.optimizePageBanner = page.getByRole('link', {
            name: 'Camunda logo Optimize',
        });
        this.identityPageBanner = page.getByRole('link', {
            name: 'Camunda logo Identity',
        });
        this.consolePageBanner = page.getByRole('link', {
            name: 'Camunda logo Console',
        });
        this.keyboardPageBanner = page.locator('#keycloak-bg');
    }
    async goTo(url, banner, sleepTimeout, maxRetries = 5) {
        const startTime = Date.now();
        let timeout = constants_1._1_SECOND_IN_MS * 1;
        if (url === '/modeler') {
            timeout = constants_1._1_SECOND_IN_MS * 10;
        }
        for (let attempt = 0; attempt < maxRetries; attempt++) {
            try {
                if (sleepTimeout) {
                    await (0, sleep_1.sleep)(sleepTimeout);
                }
                await this.page.goto(url, {
                    timeout: 60000,
                    waitUntil: 'domcontentloaded',
                });
                const loginPage = new LoginPage_1.LoginPage(this.page);
                const loginSelector = loginPage.usernameInput; // Or another unique, stable selector
                // 1. Wait for either the banner or the login page to appear first.
                await (0, test_1.expect)(banner.or(loginSelector)).toBeVisible({ timeout: 60000 });
                // 2. Now, check which one it was.
                const isBannerVisible = await banner.isVisible();
                if (isBannerVisible) {
                    // The banner is visible. This MIGHT be the page that redirects.
                    // We'll wait a few seconds to see if it "corrects itself" to the login page.
                    try {
                        // Wait specifically for the login page selector to appear.
                        await (0, test_1.expect)(loginSelector).toBeVisible({ timeout: 5000 });
                        // If we get here, a redirect occurred. Now we log in.
                        await loginPage.login(this.activeUser, this.activePassword);
                    }
                    catch (error) {
                        // The login selector did NOT appear within 5 s. Fall through to the
                        // final banner check — if a delayed Keycloak redirect fires after
                        // that window the banner will be gone and the check will throw,
                        // triggering a retry rather than silently returning on the wrong page.
                    }
                }
                else {
                    // The login page was visible from the start.
                    await loginPage.login(this.activeUser, this.activePassword);
                }
                // Final guard: confirm we actually landed on the target page.
                // A Keycloak redirect that fires more than 5 s after the banner
                // first appears (common after context.clearCookies() + long beforeEach)
                // is caught here and turns into a retry rather than a silent wrong-page return.
                await (0, test_1.expect)(banner).toBeVisible({ timeout: 30000 });
                return; // End of successful navigation/login
            }
            catch (error) {
                const now = new Date();
                const elapsed = Date.now() - startTime;
                if (attempt < maxRetries - 1) {
                    await (0, sleep_1.sleep)(5000);
                    if (!this.page.isClosed()) {
                        try {
                            await this.page.waitForLoadState('load', { timeout: timeout });
                        }
                        catch (error) {
                            const now2 = new Date();
                            const elapsed2 = Date.now() - startTime;
                            console.warn(`[${now2.toISOString()}] (+${elapsed2}ms) [NavigationPage] Load state timeout or error: ${error}`);
                        }
                    }
                }
                else {
                    console.error(`[${now.toISOString()}] (+${elapsed}ms) [NavigationPage] Login (${url}) failed after ${maxRetries} attempts`);
                    throw new Error(`Login (${url}) failed after ${maxRetries} attempts`);
                }
            }
        }
    }
    async goToModeler(sleepTimeout) {
        await this.goTo('/modeler', this.modelerPageBanner, sleepTimeout);
    }
    async goToTasklist(sleepTimeout) {
        await this.goTo('/tasklist', this.tasklistPageBanner, sleepTimeout);
    }
    async goToOperate(sleepTimeout) {
        await this.goTo('/operate', this.operatePageBanner, sleepTimeout);
    }
    async goToOptimize(sleepTimeout) {
        await this.goTo('/optimize', this.optimizePageBanner, sleepTimeout);
    }
    async goToKeycloak(maxRetries = 5) {
        const keycloakUrl = process.env.KEYCLOAK_URL
            ? `${process.env.KEYCLOAK_URL}/auth`
            : '/auth';
        let lastError;
        for (let attempt = 0; attempt < maxRetries; attempt++) {
            try {
                await this.page.goto(keycloakUrl);
                await (0, test_1.expect)(this.keyboardPageBanner).toBeVisible({ timeout: 60000 });
                return;
            }
            catch (error) {
                lastError = error;
                if (attempt < maxRetries - 1) {
                    await (0, sleep_1.sleep)(5000);
                }
            }
        }
        throw lastError instanceof Error
            ? lastError
            : new Error(`goToKeycloak failed after ${maxRetries} attempts`);
    }
    async goToIdentity(sleepTimeout) {
        await this.goTo('/identity', this.identityPageBanner, sleepTimeout);
    }
    async goToConsole(sleepTimeout) {
        await this.goTo('/console', this.consolePageBanner, sleepTimeout);
    }
}
exports.NavigationPage = NavigationPage;
