import { test, expect } from '@playwright/test';
import { acceptCookieConsent } from '../helpers/utils';

test.describe('Logout Flow', () => {
  // Use authenticated state for these tests
  test.use({ storageState: 'tests/.auth/user.json' });

  test.beforeEach(async ({ page }) => {
    // Accept cookie consent if present on any page navigation
    await acceptCookieConsent(page);
  });

  test('should successfully logout', async ({ page }) => {
    // Navigate to dashboard
    await page.goto('/app/dashboard');
    await acceptCookieConsent(page);

    // Verify we're logged in
    await expect(page.locator('body')).toContainText(/dashboard|panel de control/i);

    // Look for user menu or logout button
    // Try different common patterns
    const userMenuButton = page.getByRole('button', { name: /user|account|profile|usuario|cuenta/i }).first();

    if (await userMenuButton.isVisible().catch(() => false)) {
      await userMenuButton.click();

      // Wait for menu to open
      await page.waitForTimeout(500);
    }

    // Click logout button
    const logoutButton = page.getByRole('button', { name: /log out|logout|sign out|cerrar sesión/i });
    await logoutButton.click();

    // Should redirect to login page
    await expect(page).toHaveURL(/\/(login|$)/, { timeout: 10000 });

    // Verify we're logged out (check for login form)
    await acceptCookieConsent(page);
    await expect(page.getByLabel(/email|correo/i)).toBeVisible();
  });

  test('should not access protected routes after logout', async ({ page }) => {
    // Navigate to dashboard
    await page.goto('/app/dashboard');

    // Logout
    const userMenuButton = page.getByRole('button', { name: /user|account|profile|usuario|cuenta/i }).first();

    if (await userMenuButton.isVisible().catch(() => false)) {
      await userMenuButton.click();
      await page.waitForTimeout(500);
    }

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

    // Wait for redirect
    await page.waitForURL(/\/(login|$)/);

    // Try to access protected route
    await page.goto('/app/dashboard');

    // Should redirect back to login
    await expect(page).toHaveURL(/\/login/, { timeout: 5000 });
  });

  test('should clear user data after logout', async ({ page, context }) => {
    // Navigate to dashboard
    await page.goto('/app/dashboard');

    // Logout
    const userMenuButton = page.getByRole('button', { name: /user|account|profile|usuario|cuenta/i }).first();

    if (await userMenuButton.isVisible().catch(() => false)) {
      await userMenuButton.click();
      await page.waitForTimeout(500);
    }

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

    // Wait for redirect
    await page.waitForURL(/\/(login|$)/);

    // Check that authentication tokens are cleared
    const cookies = await context.cookies();
    const authCookies = cookies.filter((cookie) =>
      cookie.name.toLowerCase().includes('token') || cookie.name.toLowerCase().includes('auth')
    );

    // Auth cookies should be removed or expired
    expect(authCookies.length).toBe(0);
  });
});
