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

/**
 * Authentication helper functions for Playwright tests
 */

export interface LoginCredentials {
  email: string;
  password: string;
}

/**
 * Logs in a user manually (use this for tests that need fresh login)
 * For most tests, use the saved auth state instead
 */
export async function login(page: Page, credentials: LoginCredentials) {
  await page.goto('/login');

  await page.getByLabel(/email/i).fill(credentials.email);
  await page.getByLabel(/password/i).fill(credentials.password);

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

  // Wait for navigation to complete
  await page.waitForURL(/\/(app|dashboard)/);

  // Verify login success
  await expect(page.locator('body')).toContainText(/dashboard|panel de control/i);
}

/**
 * Logs out the current user
 */
export async function logout(page: Page) {
  // Look for user menu or logout button
  // Adjust selectors based on your actual app structure
  const userMenuButton = page.getByRole('button', { name: /user|account|profile/i });

  if (await userMenuButton.isVisible()) {
    await userMenuButton.click();
  }

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

  // Verify we're logged out
  await expect(page).toHaveURL(/\/(login|$)/);
}

/**
 * Verifies that the user is authenticated
 */
export async function verifyAuthenticated(page: Page) {
  // Check for authenticated state indicators
  await expect(page.locator('body')).toContainText(/dashboard|panel de control/i);
}

/**
 * Verifies that the user is NOT authenticated
 */
export async function verifyNotAuthenticated(page: Page) {
  // Should redirect to login if not authenticated
  await expect(page).toHaveURL(/\/login/);
}

/**
 * Default test credentials
 * Override with environment variables for CI/CD
 */
export const TEST_USER: LoginCredentials = {
  email: process.env.TEST_USER_EMAIL || 'test@bakery.com',
  password: process.env.TEST_USER_PASSWORD || 'test-password-123',
};

export const ADMIN_USER: LoginCredentials = {
  email: process.env.ADMIN_USER_EMAIL || 'admin@bakery.com',
  password: process.env.ADMIN_USER_PASSWORD || 'admin-password-123',
};
