/**
 * GET /api/auth/verify-email?token — foundation-auth-rbac (Task 12).
 *
 * Verifies the signed token, marks the user verified, creates their first
 * tenant + tenant_settings + system roles + OWNER membership (one audited
 * transaction in completeEmailVerification), issues access+refresh via
 * issueSessionForTenant, and redirects to app.zync.is/onboarding.
 */
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { AppEnv } from '../../types'
import { dispatchVerifyEmail } from '../../lib/auth-write-do'

export const verifyEmailRoute = new Hono<AppEnv>()

verifyEmailRoute.get('/verify-email', async (c) => {
  const token = c.req.query('token')
  if (!token) return c.json({ error: 'Missing token' }, 400)

  // Offload token-verify + JTI consume + tenant/session provisioning to
  // AuthWriteDO (30s budget, sticky isolate) to escape the stateless pool's
  // `exceededResources` kills. The DO needs the original request metadata to
  // record the session and compute the redirect origin, so forward it.
  const result = await dispatchVerifyEmail(c.env, {
    token,
    ip: c.req.header('CF-Connecting-IP') ?? null,
    ray: c.req.header('CF-Ray') ?? null,
    userAgent: c.req.header('User-Agent') ?? null,
    country: c.req.header('CF-IPCountry') ?? null,
    reqUrl: c.req.url,
  })

  // Reconstruct the client Response identically. A 302 with a redirect target
  // (optionally carrying freshly-minted session cookies) becomes a real redirect;
  // everything else is a JSON error.
  if (result.status === 302 && result.redirect) {
    if (result.setCookies) {
      for (const cookie of result.setCookies) c.header('Set-Cookie', cookie, { append: true })
    }
    return c.redirect(result.redirect, 302)
  }
  return c.json(
    (result.body ?? { error: 'Verification failed' }) as Record<string, unknown>,
    result.status as ContentfulStatusCode,
  )
})
