import { Page } from '@playwright/test';

const BASE_URL = process.env.BASE_URL ?? 'https://pbx.local:4443';
const ADMIN_USER = process.env.ADMIN_USER ?? 'admin';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD ?? 'admin';

/** Navigates to the admin portal login page and authenticates. */
export async function login(page: Page, baseUrl = BASE_URL): Promise<void> {
  await page.goto(`${baseUrl}/login`, { waitUntil: 'domcontentloaded' });

  await page
    .locator('[name="username"],[name="user"],#username,#user,input[type="text"]:first-of-type')
    .first()
    .fill(ADMIN_USER);

  await page
    .locator('[name="password"],#password,input[type="password"]')
    .first()
    .fill(ADMIN_PASSWORD);

  await page
    .locator('[type="submit"],button:has-text("Login"),button:has-text("Sign in"),button:has-text("Entrar")')
    .first()
    .click();

  await page.waitForURL(/dashboard|home|index|admin|portal/, { timeout: 20_000 });
}

export async function logout(page: Page): Promise<void> {
  await page
    .locator('button:has-text("Logout"),a:has-text("Logout"),a:has-text("Log out"),[aria-label="Logout"]')
    .first()
    .click();
}

export { BASE_URL, ADMIN_USER };
