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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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

/**
 * Global setup for authentication
 * This runs once before all tests and saves the authenticated state
 * Other tests can reuse this state to avoid logging in repeatedly
 */
setup('authenticate', async ({ page }) => {
  // Navigate to login page
  await page.goto('/login');

  // Handle cookie consent dialog if present
  const acceptCookiesButton = page.getByRole('button', {
    name: /aceptar todas|accept all/i,
  });
  if (await acceptCookiesButton.isVisible({ timeout: 2000 }).catch(() => false)) {
    await acceptCookiesButton.click();
    console.log('✅ Cookie consent accepted');
  }

  // TODO: Update these credentials with your test user
  // For now, we'll use environment variables or default test credentials
  const testEmail = process.env.TEST_USER_EMAIL || 'ualfaro@gmail.com';
  const testPassword = process.env.TEST_USER_PASSWORD || 'Admin123';

  // Fill in login form
  await page.getByLabel(/email|correo/i).fill(testEmail);
  // Use getByRole for password to avoid matching the "Show password" button
  await page.getByRole('textbox', { name: /password|contraseña/i }).fill(testPassword);

  // Click login button
  await page.getByRole('button', { name: /log in|sign in|login|acceder/i }).click();

  // Wait for redirect to dashboard or app
  await page.waitForURL(/\/(app|dashboard)/);

  // Verify we're logged in by checking for user-specific elements
  // Adjust this selector based on your actual app structure
  await expect(page.locator('body')).toContainText(/dashboard|panel de control/i, {
    timeout: 10000,
  });

  // Save authenticated state
  await page.context().storageState({ path: authFile });

  console.log('✅ Authentication setup complete');
});
