"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loginAs = loginAs;
const test_1 = require("@playwright/test");
const credentials_1 = require("./credentials");
async function loginAs(world, profileName, options = {}) {
    const page = world.page;
    if (!page) {
        throw new Error('Cannot log in before the Playwright page has been created.');
    }
    const username = (0, credentials_1.resolveCredential)(world, `${profileName}.username`);
    const password = (0, credentials_1.resolveCredential)(world, `${profileName}.password`);
    const authConfig = world.config.auth;
    const loginPath = options.loginPath ?? authConfig?.loginPath ?? '/login';
    const targetUrl = new URL(loginPath, world.config.baseUrl).toString();
    await page.goto(targetUrl);
    await fillUsername(page, username, authConfig?.usernameSelector);
    await fillPassword(page, password, authConfig?.passwordSelector);
    if (authConfig?.successUrlContains) {
        await Promise.all([
            (0, test_1.expect)(page).toHaveURL(new RegExp(escapeRegExp(authConfig.successUrlContains)), {
                timeout: world.config.timeout,
            }),
            clickSubmit(page, authConfig?.submitSelector, authConfig?.submitButtonName)
        ]);
    }
    else {
        await Promise.all([
            page.waitForLoadState('domcontentloaded', { timeout: world.config.timeout }).catch(() => undefined),
            clickSubmit(page, authConfig?.submitSelector, authConfig?.submitButtonName)
        ]);
    }
}
async function fillUsername(page, value, selector) {
    const locator = selector
        ? page.locator(selector).first()
        : await firstVisible(page.getByLabel(/user(name)?/i), page.locator('input[name="username"], input[name="userName"], input[type="email"], input[type="text"]'));
    await locator.fill(value);
}
async function fillPassword(page, value, selector) {
    const locator = selector
        ? page.locator(selector).first()
        : await firstVisible(page.getByLabel(/password/i), page.locator('input[name="password"], input[type="password"]'));
    await locator.fill(value);
}
async function clickSubmit(page, selector, buttonName) {
    const locator = selector
        ? page.locator(selector).first()
        : await firstVisible(page.getByRole('button', { name: buttonName ? new RegExp(escapeRegExp(buttonName), 'i') : /log in|login|sign in/i }), page.locator('button[type="submit"], input[type="submit"]'));
    await locator.click();
}
async function firstVisible(...locators) {
    for (const locator of locators) {
        const candidate = locator.first();
        if (await candidate.isVisible().catch(() => false)) {
            return candidate;
        }
    }
    return locators[0].first();
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
