import { test, expect } from '@playwright/test';
import { BASE_URL, TEST_USER, login, register, ensureLoggedIn, clearAuthState } from './helpers/auth';

// ─────────────────────────────────────────────────────────────────────────────
// 1. AUTH — Xác thực & Phân quyền
// ─────────────────────────────────────────────────────────────────────────────
test.describe('1. Auth — Xác thực & Phân quyền', () => {

  test('1.1 Đăng ký tài khoản user mới', async ({ page }) => {
    const newUser = `e2e_reg_${Date.now()}`;
    const ok = await register(page, newUser, 'Test12345!', `${newUser}@test.local`);
    expect(ok).toBe(true);
    await expect(page).toHaveURL(/\/app/);
  });

  test('1.2 Login thành công → redirect /app', async ({ page }) => {
    // Make sure test user exists first by trying registration (noop if exists)
    await page.goto(`${BASE_URL}/auth?mode=signup`, { waitUntil: 'domcontentloaded' });
    const usernameField = page.locator('[data-testid="auth-username"]');
    await usernameField.waitFor({ state: 'visible', timeout: 10000 });
    await usernameField.fill(TEST_USER.username);
    const emailField = page.locator('[data-testid="auth-email"]');
    if (await emailField.isVisible({ timeout: 1000 }).catch(() => false)) {
      await emailField.fill(TEST_USER.email);
    }
    await page.locator('[data-testid="auth-password"]').fill(TEST_USER.password);
    await page.locator('[data-testid="auth-submit"]').click();
    // Either registers or shows "already exists" — either way we're done with setup
    await page.waitForTimeout(1500);

    // Now do the actual login test
    const ok = await login(page);
    expect(ok).toBe(true);
    await expect(page).toHaveURL(/\/app/);
  });

  test('1.3 Sai mật khẩu → hiển thị thông báo lỗi', async ({ page }) => {
    await page.goto(`${BASE_URL}/auth`, { waitUntil: 'domcontentloaded' });
    await page.locator('[data-testid="auth-username"]').waitFor({ state: 'visible', timeout: 10000 });
    await page.locator('[data-testid="auth-username"]').fill('completely_invalid_user_9999');
    await page.locator('[data-testid="auth-password"]').fill('WrongPassword!');
    await page.locator('[data-testid="auth-submit"]').click();

    // Toast error should appear
    const errorToast = page
      .locator('[class*="toast"]')
      .or(page.getByText(/failed|error|incorrect|invalid|không đúng|sai/i).first());
    await expect(errorToast).toBeVisible({ timeout: 8000 });
  });

  test('1.4 Route bảo vệ — /app redirect về /auth khi chưa đăng nhập', async ({ page }) => {
    await clearAuthState(page);
    await page.goto(`${BASE_URL}/app`, { waitUntil: 'domcontentloaded' });
    await expect(page).toHaveURL(/auth|signin|login/, { timeout: 12000 });
  });

  test('1.5 Toggle Sign Up / Sign In form', async ({ page }) => {
    await page.goto(`${BASE_URL}/auth`, { waitUntil: 'domcontentloaded' });
    await page.locator('[data-testid="auth-username"]').waitFor({ state: 'visible', timeout: 10000 });

    // Click toggle to signup
    await page.locator('[data-testid="auth-toggle"]').click();
    // Email field should now be visible (signup mode)
    await expect(page.locator('[data-testid="auth-email"]')).toBeVisible({ timeout: 5000 });

    // Toggle back to signin
    await page.locator('[data-testid="auth-toggle"]').click();
    await expect(page.locator('[data-testid="auth-email"]')).not.toBeVisible({ timeout: 5000 });
  });
});
