/**
 * Login helpers using dev endpoints.
 * These set real httpOnly JWT cookies so all middleware works naturally.
 */

/**
 * Login as admin via the dev test-login endpoint.
 * Creates a test admin user if none exists and sets the auth cookie.
 * Waits for networkidle so the client-side auth check (admin middleware +
 * auth-init plugin) completes before the test navigates anywhere.
 */
export async function loginAsAdmin(page) {
  await page.goto('/api/dev/test-login', { waitUntil: 'domcontentloaded' })

  // The endpoint sets the cookie and redirects to /admin.
  // waitForURL fires as soon as the URL changes — not when JS finishes.
  // waitForLoadState('networkidle') ensures the auth-init plugin and admin
  // middleware have both completed their checkMemberStatus() calls before
  // the test proceeds.
  try {
    await page.waitForURL(/\/admin/, { timeout: 15000 })
    await page.waitForLoadState('networkidle')
  } catch {
    // Cookie should be set even if redirect failed — navigate manually
    await page.goto('/admin', { waitUntil: 'networkidle' })
    await page.waitForURL(/\/admin/)
  }
}

/**
 * Login as a specific member by email via the dev member-login endpoint.
 */
export async function loginAsMember(page, email) {
  await page.goto(`/api/dev/member-login?email=${encodeURIComponent(email)}`, { waitUntil: 'domcontentloaded' })
  await page.waitForURL(/\/member\//)
}
