// e2e/auth.setup.ts

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

const authFile = path.join(__dirname, '../playwright/.auth/user.json');

setup('authenticate with Microsoft Entra ID', async ({ page }) => {
  // 1. Open the Angular landing page
  await page.goto('/');

  // 2. Click your Angular login button (adjust the button name to match your UI)
  await page.getByRole('button', { name: /sign in|login/i }).click();

  // 3. Handle the Microsoft Entra ID login redirect
  await page.waitForURL(/login\.microsoftonline\.com/);

  // Enter email/UPN
  await page.locator('input[type="email"]').fill(process.env.E2E_ENTRA_USERNAME!);
  await page.locator('input[type="submit"]').click();

  // Enter password
  await page.locator('input[type="password"]').fill(process.env.E2E_ENTRA_PASSWORD!);
  await page.locator('input[type="submit"]').click();

  // Handle the optional "Stay signed in?" prompt
  const staySignedInBtn = page.locator('input[type="submit"][value="Yes"]');
  if (await staySignedInBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
    await staySignedInBtn.click();
  }

  // 4. Wait for MSAL to redirect back to your Angular app and finish exchanging tokens
  await page.waitForURL('http://localhost:4200/**');
  await expect(page.getByRole('button', { name: /logout|sign out/i })).toBeVisible();

  // 5. Save the authenticated storage state (MSAL tokens in localStorage/cookies)
  await page.context().storageState({ path: authFile });
});

