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

const AUTH_FILE = 'e2e/.auth/session.json'

/**
 * Authentication setup: selects the first available profile
 * to establish a session cookie before running any test.
 *
 * The app uses a profile-based session system:
 * - GET  /api/session/profiles  → list available profiles
 * - POST /api/session/profile   → activate a profile (sets cookie)
 *
 * The global middleware (profile.global.ts) redirects to /profiles
 * if no active profile is found.
 */
setup('select a profile to authenticate', async ({ page }) => {
  // Go to the profiles page
  await page.goto('/profiles')

  // Wait for profiles to load
  await expect(page.getByRole('heading', { name: 'Choisir un profil' })).toBeVisible({ timeout: 15_000 })

  // Wait for at least one profile button to appear
  const profileButton = page.locator('button.btn-outline').first()
  await expect(profileButton).toBeVisible({ timeout: 10_000 })

  // Click the first available profile
  await profileButton.click()

  // Wait for redirect to home page (profile selected → session cookie set)
  await page.waitForURL('/', { timeout: 10_000 })

  // Save authenticated state (cookies + localStorage)
  await page.context().storageState({ path: AUTH_FILE })
})
