/**
 * POST /api/auth/login — foundation-auth-rbac (Task 12) + auth-2fa (Task 5).
 *
 * Verifies the password (PBKDF2), then either:
 *   1. Device-trust bypass: valid `zync_device_trust` cookie → full JWT directly
 *   2. 2FA challenge: user has 2FA enabled → pending_2fa temp session token
 *   3. Forced setup: tenant enforces 2FA but user hasn't enrolled → pending_2fa_setup
 *   4. Direct issue: no 2FA configured → full JWT (existing flow)
 *
 * Defences:
 *   - RATE_LIMITER_AUTH: 10 attempts / 15min / IP (binding-backed).
 *   - KV failure counter: exponential backoff after 5, lockout after 10.
 *   - Wrong password and unknown account return the SAME 401 (no enumeration).
 */
import { Hono } from 'hono'
import type { AppEnv } from '../../types'
import { loginSchema } from '../../schemas/auth'
import { dispatchLogin } from '../../lib/auth-write-do'
import { getAppOrigins } from '../../lib/origins'

export const loginRoute = new Hono<AppEnv>()

loginRoute.post('/login', async (c) => {
  const origin = c.req.header('Origin')
  const allowedOrigins = getAppOrigins({
    environment: (c.env as { ENVIRONMENT?: string }).ENVIRONMENT,
  })
  if (!origin || !allowedOrigins.has(origin)) {
    return c.json({ error: 'Forbidden: invalid Origin' }, 403)
  }

  const ip = c.req.header('CF-Connecting-IP') ?? 'unknown'

  // Binding-backed IP rate limit (10/15min configured on RATE_LIMITER_AUTH).
  if (!c.env.RATE_LIMITER_AUTH) {
    return c.json({ error: 'Service unavailable' }, 503)
  }
  let rl: { success: boolean }
  try {
    rl = await c.env.RATE_LIMITER_AUTH.limit({ key: `login:${ip}` })
  } catch {
    return c.json({ error: 'Service unavailable' }, 503)
  }
  if (!rl.success) {
    return c.json({ error: 'Too many requests' }, 429)
  }

  const parsed = loginSchema.safeParse(await c.req.json())
  if (!parsed.success) {
    return c.json({ error: 'Invalid request' }, 400)
  }
  const { email, password } = parsed.data
  const forwardedHeaders: Record<string, string> = {}
  for (const name of ['cookie', 'cf-connecting-ip', 'cf-ipcountry', 'cf-ray', 'user-agent']) {
    const value = c.req.header(name)
    if (value) forwardedHeaders[name] = value
  }

  return dispatchLogin(c.env, {
    email,
    password,
    reqUrl: c.req.url,
    headers: forwardedHeaders,
  })
})
