/**
 * Registration Flow Tests
 *
 * Tests new user registration through real SSO.
 */

import { test, expect, TEST_ACCOUNTS } from '@platform/e2e-auth';

test.describe('Registration Flow', () => {
  // Generate unique email for each test run
  const uniqueEmail = () => `e2e-reg-${Date.now()}-${Math.random().toString(36).slice(2)}@atlilith.test`;
  const uniqueUsername = () => `e2e-user-${Date.now().toString(36)}`;

  test.beforeEach(async ({ page }) => {
    // Clear any existing session
    await page.evaluate(() => {
      localStorage.clear();
      sessionStorage.clear();
    });
  });

  test('should display registration form', async ({ page }) => {
    await page.goto('/register');

    // Should show registration form elements
    await expect(page.locator('input[name="email"], [data-testid="email-input"]')).toBeVisible();
    await expect(page.locator('input[name="username"], [data-testid="username-input"]')).toBeVisible();
    await expect(page.locator('input[name="password"], [data-testid="password-input"]')).toBeVisible();
  });

  test('should register new user and auto-login', async ({ page }) => {
    const email = uniqueEmail();
    const username = uniqueUsername();
    const password = 'NewUserPass123!';

    await page.goto('/register');

    // Fill registration form
    await page.fill('input[name="email"], [data-testid="email-input"]', email);
    await page.fill('input[name="username"], [data-testid="username-input"]', username);
    await page.fill('input[name="password"], [data-testid="password-input"]', password);

    // Fill confirm password if present
    const confirmPassword = page.locator('input[name="confirmPassword"], [data-testid="confirm-password-input"]');
    if (await confirmPassword.isVisible()) {
      await confirmPassword.fill(password);
    }

    // Accept terms if present
    const termsCheckbox = page.locator('[data-testid="terms-checkbox"], input[name="acceptTerms"]');
    if (await termsCheckbox.isVisible()) {
      await termsCheckbox.check();
    }

    // Submit
    await page.click('button[type="submit"], [data-testid="register-button"]');

    // Should be logged in after registration
    await expect(page).toHaveURL(/\/(dashboard|home|onboarding|verify)/, { timeout: 15000 });

    // Should have session token
    const token = await page.evaluate(() => localStorage.getItem('lilith_session'));
    expect(token).toBeTruthy();
  });

  test('should register via API fixture', async ({ ssoApi }) => {
    const email = uniqueEmail();
    const username = uniqueUsername();

    const response = await ssoApi.register({
      email,
      username,
      password: 'NewUserPass123!',
    });

    expect(response.sessionId).toBeTruthy();
    expect(response.user.email).toBe(email);
    expect(response.user.username).toBe(username);
  });

  test('should reject duplicate email', async ({ page }) => {
    // Try to register with existing test account email
    await page.goto('/register');

    await page.fill('input[name="email"], [data-testid="email-input"]', TEST_ACCOUNTS.worker.email);
    await page.fill('input[name="username"], [data-testid="username-input"]', uniqueUsername());
    await page.fill('input[name="password"], [data-testid="password-input"]', 'DuplicatePass123!');

    const confirmPassword = page.locator('input[name="confirmPassword"], [data-testid="confirm-password-input"]');
    if (await confirmPassword.isVisible()) {
      await confirmPassword.fill('DuplicatePass123!');
    }

    const termsCheckbox = page.locator('[data-testid="terms-checkbox"], input[name="acceptTerms"]');
    if (await termsCheckbox.isVisible()) {
      await termsCheckbox.check();
    }

    await page.click('button[type="submit"], [data-testid="register-button"]');

    // Should show error
    await expect(page.locator('[data-testid="register-error"], .error-message, [role="alert"]')).toBeVisible({
      timeout: 5000,
    });

    // Should NOT have session token
    const token = await page.evaluate(() => localStorage.getItem('lilith_session'));
    expect(token).toBeFalsy();
  });

  test('should reject weak password', async ({ page }) => {
    await page.goto('/register');

    await page.fill('input[name="email"], [data-testid="email-input"]', uniqueEmail());
    await page.fill('input[name="username"], [data-testid="username-input"]', uniqueUsername());
    await page.fill('input[name="password"], [data-testid="password-input"]', 'weak');

    const confirmPassword = page.locator('input[name="confirmPassword"], [data-testid="confirm-password-input"]');
    if (await confirmPassword.isVisible()) {
      await confirmPassword.fill('weak');
    }

    await page.click('button[type="submit"], [data-testid="register-button"]');

    // Should show validation error (either inline or on submit)
    await expect(
      page.locator('[data-testid="password-error"], [data-testid="register-error"], .error-message, [role="alert"]')
    ).toBeVisible({ timeout: 5000 });
  });
});
