/**
 * Auth helpers for Playwright e2e tests.
 *
 * Provides utilities for logging in as a test user.
 * The app uses email-only registration (magic-link flow for initial confirmation)
 * and email+password for subsequent logins.
 */

import { Page } from "@playwright/test";

export const TEST_USER = {
  email: process.env.PLAYWRIGHT_EMAIL || "test@firehose.test",
  password: process.env.PLAYWRIGHT_PASSWORD || "testpassword123!",
};

/**
 * Navigate to the login page, fill in credentials, and submit.
 * Returns the page after successful login (redirected to home).
 */
export async function loginAsTestUser(page: Page) {
  await page.goto("/users/log-in");
  // Use the password-based login form
  await page.getByLabel("Email").fill(TEST_USER.email);
  await page.getByLabel("Password").fill(TEST_USER.password);
  // Click "Log in and stay logged in"
  await page.getByRole("button", { name: /log in and stay logged in/i }).click();
  await page.waitForURL("/");
}

/**
 * Navigate to the registration page, fill in email, and submit.
 * Note: In dev mode, registration is invite-only by default. Set
 * `PLAYWRIGHT_ALLOW_REGISTRATION=true` to run tests against a server
 * with open registration enabled.
 */
export async function registerTestUser(page: Page) {
  await page.goto("/users/register");
  await page.getByLabel("Email").fill(TEST_USER.email);
  await page.getByRole("button", { name: /create an account/i }).click();
  await page.waitForURL("/users/log-in");
}