/**
 * User communication preference query helpers — system-communications-notifications.
 *
 * These are consumed by notification adapter canDeliver() checks and deliver()
 * locale resolution. No raw schema tables are exposed outside this module.
 */
import { and, eq } from 'drizzle-orm'
import type { Db } from '../client'
import { users, userPreferences } from '../schema'

/**
 * Get a user's email notification opt-in list from user_preferences.
 * Returns null if no preferences row exists (treat as no subscriptions).
 */
export async function getUserEmailPrefs(
  db: Db,
  userId: string,
  tenantId: string,
): Promise<{ emailTypes: string[] } | null> {
  const rows = await db
    .select({ notificationChannels: userPreferences.notificationChannels })
    .from(userPreferences)
    .where(and(eq(userPreferences.userId, userId), eq(userPreferences.tenantId, tenantId)))
    .limit(1)

  const row = rows[0]
  if (!row) return null

  const channels = row.notificationChannels as {
    email?: string[]
    telegram?: string[]
  } | null

  return {
    emailTypes: channels?.email ?? [],
  }
}

/**
 * Get a user's Telegram notification opt-in list.
 */
export async function getUserTelegramPrefs(
  db: Db,
  userId: string,
  tenantId: string,
): Promise<{ telegramTypes: string[] } | null> {
  const rows = await db
    .select({ notificationChannels: userPreferences.notificationChannels })
    .from(userPreferences)
    .where(and(eq(userPreferences.userId, userId), eq(userPreferences.tenantId, tenantId)))
    .limit(1)

  const row = rows[0]
  if (!row) return null

  const channels = row.notificationChannels as {
    email?: string[]
    telegram?: string[]
  } | null

  return {
    telegramTypes: channels?.telegram ?? [],
  }
}

/**
 * Get a user's email address and preferred locale for notification rendering.
 * Returns null if user not found.
 */
export async function getUserEmailAndLocale(
  db: Db,
  userId: string,
  tenantId: string,
): Promise<{ email: string; locale: string | null } | null> {
  // LEFT JOIN on user_preferences to get locale preference
  const userRows = await db
    .select({ email: users.email })
    .from(users)
    .where(eq(users.id, userId))
    .limit(1)

  const userRow = userRows[0]
  if (!userRow) return null

  const prefRows = await db
    .select({ locale: userPreferences.locale })
    .from(userPreferences)
    .where(and(eq(userPreferences.userId, userId), eq(userPreferences.tenantId, tenantId)))
    .limit(1)

  const locale = prefRows[0]?.locale ?? null

  return { email: userRow.email, locale }
}

/**
 * Get the Telegram chat ID linked to a user (stored in user_preferences metadata).
 * Returns null if not linked.
 */
export async function getUserTelegramChatId(
  db: Db,
  userId: string,
  tenantId: string,
): Promise<string | null> {
  const rows = await db
    .select({ notificationChannels: userPreferences.notificationChannels })
    .from(userPreferences)
    .where(and(eq(userPreferences.userId, userId), eq(userPreferences.tenantId, tenantId)))
    .limit(1)

  const row = rows[0]
  if (!row) return null

  // telegramChatId is stored as a metadata field on notification_channels
  const channels = row.notificationChannels as {
    email?: string[]
    telegram?: string[]
    telegramChatId?: string
  } | null

  return channels?.telegramChatId ?? null
}
