/**
 * Session re-issue 2FA flags — auth-2fa.
 *
 * Mirrors login.ts: `enforce2fa` comes from the target tenant's DB setting.
 * `twoFactorVerified` carries over only when a prior session proved 2FA for the
 * same tenant (refresh); never across tenants (switch-tenant) or on invite-accept.
 */
import { verifySession } from '@zync/auth'
import { getTenant2FASettings, type Db } from '@zync/db/queries'
import type { SessionPayload, TenantId } from '@zync/types'
import type { Context } from 'hono'
import { getCookie } from 'hono/cookie'
import type { AppEnv } from '../types'
import { SESSION_COOKIE } from './cookies'

export interface TwoFactorOpts {
  enforce2fa: boolean
  twoFactorVerified: boolean
}

/** Load tenant enforcement + optional carry-over of verified state (same tenant only). */
export async function loadTwoFactorOptsForTenant(
  db: Db,
  tenantId: TenantId,
  priorSession?: SessionPayload | null,
): Promise<TwoFactorOpts> {
  const tenant2fa = await getTenant2FASettings(db, tenantId)
  const enforce2fa = tenant2fa?.enforce2fa ?? false
  const twoFactorVerified =
    priorSession?.tid === tenantId && priorSession.two_factor_verified === true
  return { enforce2fa, twoFactorVerified }
}

/** Best-effort parse of the outgoing access cookie (refresh sends both cookies). */
export async function parsePriorSessionFromRequest(
  c: Context<AppEnv>,
): Promise<SessionPayload | null> {
  const token = getCookie(c, SESSION_COOKIE)
  if (!token) return null
  try {
    return await verifySession(token, c.env.JWT_SECRET)
  } catch {
    return null
  }
}
