import { test as base, Page } from '@playwright/test';
import { generateTOTP } from '../utils/totp';
import {dismissSplashPage} from "../utils/dismiss-splash-page";

// Test credentials from environment variables
const LOGIN_URL = process.env.LOGIN_URL || 'https://sso.uat.bgl360.com.au/?app=smartdocs&&appFilter=smartdocs';
const USERNAME = process.env.USERNAME || '';
const PASSWORD = process.env.PASSWORD || '';
const TOTP_KEY = process.env.TOTP_KEY || '';

type AuthFixtures = {
  loggedInPage: Page;
  testStartTime: number;
};

export const test = base.extend<AuthFixtures>({
  testStartTime: [async ({}, use) => {
    const startTime = Date.now();
    await use(startTime);
  }, { auto: true }],

  loggedInPage: async ({ page, testStartTime }, use) => {
    // Step 1: Navigate to login page
    await page.goto(LOGIN_URL);

    // Step 2: Enter credentials and submit
    await page.getByTestId('username-input').fill(USERNAME);
    await page.getByTestId('password-input').fill(PASSWORD);
    await page.getByTestId('submit-button').click();

    // Step 3: Wait for MFA page and handle TOTP
    const securityCodeInput = page.getByRole('textbox', { name: 'Enter Security Code' });
    await securityCodeInput.waitFor({ state: 'visible' });

    // Generate and enter TOTP code
    const totpCode = generateTOTP(TOTP_KEY);
    await securityCodeInput.fill(totpCode);

    // Step 4: Submit MFA
    await page.getByRole('button', { name: 'Submit' }).click();

    // Step 5: Wait for successful login (redirect to entities page)
    await page.waitForURL(/\/host\/#\//);

    // Step 6: Dismiss Splash Page
    await dismissSplashPage(page)

    // Provide the logged-in page to the test
    await use(page);

    // After the test completes, ensure at least 30 seconds have elapsed
    const elapsedTime = Date.now() - testStartTime;
    const minimumTestDuration = 30000; // 30 seconds

    if (elapsedTime < minimumTestDuration) {
      const waitTime = minimumTestDuration - elapsedTime;
      console.log(`Waiting ${waitTime}ms to ensure 30s minimum test duration (TOTP constraint)`);
      await page.waitForTimeout(waitTime);
    }
  },
});

export { expect } from '@playwright/test';
