/**
 * GET /api/auth/me — foundation-auth-rbac (Task 12).
 *
 * Returns the current identity + tenant + role + expanded permissions, joined
 * via getMeView. 30s CDN cache, `Vary: Authorization`. Mounted behind
 * authMiddleware (401 on expired/blocklisted handled there).
 */
import { Hono } from 'hono'
import { createDb, getMeView, getUser2FAStatus } from '@zync/db/queries'
import type { Locale, TenantId, UserId } from '@zync/types'
import type { AppEnv } from '../../types'

export const meRoute = new Hono<AppEnv>()

function coerceLocale(value: unknown): Locale | null {
  return value === 'en' || value === 'he' ? value : null
}

meRoute.get('/me', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user') {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  if (!session.tid) {
    return c.json({ error: 'No active tenant' }, 409)
  }

  const db = createDb(c.env)
  const userId = session.sub as UserId
  const tenantId = session.tid as TenantId
  const [view, twoFactor] = await Promise.all([
    getMeView(db, userId, tenantId),
    getUser2FAStatus(db, userId),
  ])
  if (!view) return c.json({ error: 'Membership not found' }, 404)

  c.header('Cache-Control', 'private, max-age=30')
  c.header('Vary', 'Authorization')

  const locale = coerceLocale(view.userLocale) ?? coerceLocale(view.tenantLocale)
  const timezone = view.userTimezone ?? view.tenantDefaultTimezone
  const defaultCurrency = view.userDefaultCurrency ?? view.tenantDefaultCurrency

  return c.json({
    id: view.id,
    email: view.email,
    name: view.name,
    avatarUrl: view.avatarUrl,
    tenantId: view.tenantId,
    tenantSlug: view.tenantSlug,
    tenantName: (view as { tenantName?: string | null }).tenantName ?? null,
    role: view.role,
    tier: view.tier,
    permissions: view.permissions,
    locale,
    timezone,
    countryCode: view.countryCode,
    defaultCurrency,
    onboarding_completed: view.onboardingCompleted,
    onboarding_step: view.onboardingStep,
    emailVerified: view.emailVerifiedAt !== null,
    // 2FA enablement is owned by auth-2fa; no 2FA columns in this wave.
    twoFactorEnabled: twoFactor?.twoFactorEnabled ?? false,
    // admin-impersonation: impersonation session fields
    impersonation: session.impersonation === true ? true : undefined,
    impersonatingAdminId: session.impersonating_admin_id,
    exp: session.exp,
  })
})
