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

/**
 * Login Flow Tests
 * Generated from: specs/auth/login-flow.md
 *
 * Tests the authentication functionality of Open Core Business Suite
 */
test.describe('Login Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Navigate to login page before each test
    await page.goto('/auth/login', { waitUntil: 'networkidle' });
  });

  test('should display login form', async ({ page }) => {
    // Verify login page elements are visible
    await expect(page.locator('#formAuthentication')).toBeVisible();
    await expect(page.locator('#email')).toBeVisible();
    await expect(page.locator('#password')).toBeVisible();
    await expect(page.locator('button[type="submit"]')).toBeVisible();
  });

  test('should login with valid admin credentials', async ({ page }) => {
    // Fill in admin credentials
    await page.locator('#email').fill('admin@demo.com');
    await page.locator('#password').fill('password123');

    // Click submit and wait for navigation
    await page.locator('button[type="submit"]').click();
    await page.waitForURL('**/dashboard', { timeout: 15000 });

    // Verify dashboard loaded
    await expect(page).toHaveURL(/.*dashboard/);
  });

  test('should show error with invalid password', async ({ page }) => {
    // Fill in credentials with wrong password
    await page.locator('#email').fill('admin@demo.com');
    await page.locator('#password').fill('wrongpassword');

    // Submit the form
    await page.locator('button[type="submit"]').click();

    // Wait for page to process the request
    await page.waitForLoadState('networkidle');

    // Verify still on login page (not redirected to dashboard)
    await expect(page).toHaveURL(/.*login/);
  });

  test('should show error with non-existent user', async ({ page }) => {
    // Fill in non-existent user credentials
    await page.locator('#email').fill('nonexistent@example.com');
    await page.locator('#password').fill('password123');

    // Submit the form
    await page.locator('button[type="submit"]').click();

    // Wait for page to process the request
    await page.waitForLoadState('networkidle');

    // Verify still on login page
    await expect(page).toHaveURL(/.*login/);
  });
});
