"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasePage = void 0;
const test_1 = require("@playwright/test");
const logger_1 = require("../../utils/logger");
const timeouts_1 = require("../../timeouts");
const BasePage_locators_1 = require("./BasePage.locators");
const FormHelper_1 = require("./helpers/FormHelper/FormHelper");
const RowActionsHelper_1 = require("./helpers/RowActionsHelper/RowActionsHelper");
const CertificateHelper_1 = require("./helpers/CertificateHelper");
const RowActionsOrchestrator_1 = require("../shared/RowActionsOrchestrator");
const TextUtils_1 = require("./utils/TextUtils");
const UiNotificationService_1 = require("../shared/notifications/UiNotificationService");
const ModalWindowService_1 = require("../shared/modal/ModalWindowService");
const VisibilityChecker_1 = require("../shared/visibility/VisibilityChecker");
class BasePage {
    constructor(page) {
        this.page = page;
        const locators = (0, BasePage_locators_1.createBasePageLocators)(page);
        this.modalDialog = locators.modalDialog;
        this.commonModalWindowButtons = locators.commonModalWindowButtons;
        this.orgCoreTextFields = locators.orgCoreTextFields;
        this.userCoreTextFields = locators.userCoreTextFields;
        this.uiNotifications = new UiNotificationService_1.UiNotificationService(page);
        this.modalWindowService = new ModalWindowService_1.ModalWindowService(page, this.modalDialog, this.uiNotifications);
        this.visibilityChecker = new VisibilityChecker_1.VisibilityChecker();
        this.formHelper = new FormHelper_1.FormHelper(page);
        this.rowActionsHelper = new RowActionsHelper_1.RowActionsHelper(page, this.modalDialog, this.formHelper, this.uiNotifications, () => this.confirmAction());
        this.certificateHelper = new CertificateHelper_1.CertificateHelper(page, () => this.getRoleOrThrow(), this.uiNotifications);
        this.textUtils = new TextUtils_1.TextUtils();
        this.rowActionsOrchestrator = new RowActionsOrchestrator_1.RowActionsOrchestrator(this.rowActionsHelper);
    }
    setRole(role) {
        this.role = role;
    }
    getRoleOrThrow() {
        if (!this.role) {
            throw new Error(`Роль не установлена для ${this.constructor.name}. Вызовите setRole(role) в фикстуре перед использованием методов, зависящих от роли.`);
        }
        return this.role;
    }
    getCommonModalWindowButtons() {
        return this.commonModalWindowButtons;
    }
    getModalDialog() {
        return this.modalDialog;
    }
    getOrgCoreTextFields() {
        return this.orgCoreTextFields;
    }
    getUserCoreTextFields() {
        return this.userCoreTextFields;
    }
    async goto(path) {
        try {
            await this.page.goto(path);
            logger_1.logger.debug(`Успешный переход на страницу: ${path}`, `${this.constructor.name}.goto`);
        }
        catch (error) {
            logger_1.logger.error(`Ошибка при переходе на ${path}: ${error}`, `${this.constructor.name}.goto`);
            throw error;
        }
    }
    async reloadPage() {
        await test_1.test.step('Обновление страницы', async () => {
            try {
                await this.page.reload();
                logger_1.logger.debug('Страница обновлена', `${this.constructor.name}.reloadPage`);
            }
            catch (error) {
                logger_1.logger.error(`Ошибка при обновлении страницы: ${error}`, `${this.constructor.name}.reloadPage`);
                throw error;
            }
        });
    }
    async scrollToElement(locator) {
        await locator.waitFor({ state: 'attached', timeout: (0, timeouts_1.getTimeouts)().NAVIGATION });
        await locator.waitFor({ state: 'visible', timeout: (0, timeouts_1.getTimeouts)().NAVIGATION });
        await locator.scrollIntoViewIfNeeded({ timeout: (0, timeouts_1.getTimeouts)().ACTION });
    }
    /**
     * Выполняет действие; после завершения и при ошибке проверяет toast-уведомления UI.
     * @param actionDescription — описание действия в предложном падеже, например «сохранении блока X»
     * @param action — шаги, которые могут завершиться ошибкой
     * @returns результат выполнения `action`
     */
    async executeWithErrorCheck(actionDescription, action) {
        return this.uiNotifications.executeWithErrorCheck(actionDescription, action);
    }
    async assertNoErrorMessages() {
        return this.uiNotifications.assertNoErrors(this.constructor.name);
    }
    async performModalTerminalActionToCloseModalWindow(terminalButton, stepName = 'Терминальное действие модального окна', haveNextStep) {
        return this.modalWindowService.performTerminalAction(terminalButton, this.constructor.name, stepName, haveNextStep);
    }
    async confirmAction(haveNextStep) {
        return this.modalWindowService.confirmAction(this.constructor.name, haveNextStep);
    }
    async checkPageTitle(title) {
        await test_1.test.step(`Проверка заголовка страницы "${title}"`, async () => {
            await this.page.waitForLoadState('networkidle', { timeout: (0, timeouts_1.getTimeouts)().PAGE_LOAD });
            await (0, test_1.expect)(this.page).toHaveTitle(title);
        });
    }
    async checkSuccessMessage(message) {
        return this.uiNotifications.checkSuccessMessage(message);
    }
}
exports.BasePage = BasePage;
