import { waitForLatestOtc, clearMailpit } from './mailpit.js'

// Sign in and leave the rfc_session cookie on the page's browser context
// (page.request shares the page context's cookie jar, so a subsequent
// page.goto is authenticated). Two paths, chosen by environment:
//
//   * DEPLOYED (PPE): when E2E_TEST_AUTH_SECRET is set, use the gated
//     `/auth/test/login` shortcut (v0.52.0). The deployed env has no
//     Mailpit sink to read an OTC code from, so the suite presents the
//     shared secret and the server mints an owner session for the one
//     configured E2E_TEST_AUTH_EMAIL. See backend/app/main.py.
//   * LOCAL (Tier-1 docker stack): no secret set → the original §6.2 OTC
//     path through Mailpit. The Tier-1 backend-seed pre-grants
//     e2e-owner@example.test as a deployment owner, so signing in as that
//     address yields write access (SLICE-4/5).
//
// OWNER_EMAIL is the identity both paths sign in as: E2E_OWNER_EMAIL when
// set (PPE points it at E2E_TEST_AUTH_EMAIL), else the Tier-1 default.
export const OWNER_EMAIL =
  process.env.E2E_OWNER_EMAIL || 'e2e-owner@example.test'

export async function signIn(page, email) {
  const secret = process.env.E2E_TEST_AUTH_SECRET
  if (secret) {
    const r = await page.request.post('/auth/test/login', {
      data: { email },
      headers: { 'X-Test-Auth-Secret': secret },
    })
    if (!r.ok()) throw new Error(`test-auth login failed: ${r.status()} ${await r.text()}`)
    return
  }

  // Local Tier-1 OTC path through Mailpit.
  await clearMailpit()
  const req = await page.request.post('/auth/otc/request', { data: { email } })
  if (!req.ok()) throw new Error(`otc request failed: ${req.status()}`)
  const code = await waitForLatestOtc(email)
  const verify = await page.request.post('/auth/otc/verify', { data: { email, code } })
  if (!verify.ok()) throw new Error(`otc verify failed: ${verify.status()}`)
}
