/**
 * Two-factor auth read helpers — auth-2fa.
 *
 * Queries that need both user + tenant data for 2FA flow decisions.
 */
import { and, count, eq } from 'drizzle-orm'
import type { TenantId, UserId } from '@zync/types'
import type { Db } from '../client'
import { users, tenants, tenantMemberships } from '../schema'

export interface UserWith2FA {
  id: string
  twoFactorEnabled: boolean
  twoFactorPhone: string | null
  twoFactorPhoneSuffix: string | null
}

export interface TenantWith2FA {
  enforce2fa: boolean
  disable2faRememberDevice: boolean
}

/** Get 2FA fields for a user. */
export async function getUser2FAStatus(db: Db, userId: UserId): Promise<UserWith2FA | null> {
  const [row] = await db
    .select({
      id: users.id,
      twoFactorEnabled: users.twoFactorEnabled,
      twoFactorPhone: users.twoFactorPhone,
      twoFactorPhoneSuffix: users.twoFactorPhoneSuffix,
    })
    .from(users)
    .where(eq(users.id, userId))
    .limit(1)
  return row ?? null
}

/** Get 2FA enforcement settings for a tenant. */
export async function getTenant2FASettings(
  db: Db,
  tenantId: TenantId,
): Promise<TenantWith2FA | null> {
  const [row] = await db
    .select({
      enforce2fa: tenants.enforce2fa,
      disable2faRememberDevice: tenants.disable2faRememberDevice,
    })
    .from(tenants)
    .where(eq(tenants.id, tenantId))
    .limit(1)
  return row ?? null
}

/** Count how many active members have 2FA enabled vs total. */
export async function getMember2FAStats(
  db: Db,
  tenantId: TenantId,
): Promise<{ enabled: number; total: number }> {
  const rows = await db
    .select({
      twoFactorEnabled: users.twoFactorEnabled,
      count: count(),
    })
    .from(tenantMemberships)
    .innerJoin(users, eq(users.id, tenantMemberships.userId))
    .where(and(eq(tenantMemberships.tenantId, tenantId), eq(tenantMemberships.status, 'active')))
    .groupBy(users.twoFactorEnabled)

  let total = 0
  let enabled = 0
  for (const r of rows) {
    total += r.count
    if (r.twoFactorEnabled) enabled += r.count
  }
  return { enabled, total }
}

/** Get all active member user IDs for a tenant (for bumping user_version). */
export async function getActiveMemberIds(db: Db, tenantId: TenantId): Promise<string[]> {
  const rows = await db
    .select({ userId: tenantMemberships.userId })
    .from(tenantMemberships)
    .where(and(eq(tenantMemberships.tenantId, tenantId), eq(tenantMemberships.status, 'active')))
  return rows.map((r) => r.userId)
}
