import { test as setup, expect } from '@playwright/test';

const authFile = 'tests/e2e/.auth/user.json';

setup('authenticate', async ({ page }) => {
    // Use credentials from the SetupTestTenant command
    // Ideally these should be environment variables or consistent with the command
    const email = 'test@example.com';
    const password = 'password';

    await page.goto('/login');

    await page.getByLabel('Email').fill(email);
    await page.getByLabel('Password').fill(password);
    await page.getByRole('button', { name: 'Login to your account' }).click();

    // Wait for navigation
    await page.waitForLoadState('networkidle');

    // Wait until the page receives the cookies.
    //
    // Sometimes login flow sets cookies in the process of several redirects.
    // Wait for the final URL to ensure that the cookies are actually set.
    // Wait for the page to reach a state where all cookies are set.
    // We check for the User Menu button which appears only when logged in.
    // The button typically displays the user's name.

    // Capture screenshot for debugging
    await page.screenshot({ path: 'test-results/after-login.png', fullPage: true });

    // Verify successful authentication by checking URL changed from /login
    // Note: Dashboard may have errors due to missing tenant data, but auth is successful
    await expect(page).not.toHaveURL(/\/login$/);
    await expect(page).toHaveURL(/\//); // Should be at root or redirected page

    // End of authentication steps.

    await page.context().storageState({ path: authFile });
});
