/**
 * createNotification helper — system-communications-notifications (Task 12).
 *
 * Inserts a notification row, then fires best-effort:
 *   1. pushOverWebSocket (synchronous KV lookup + DO forward)
 *   2. deliverNotification fanout (email / telegram / push) — fire-and-forget
 *
 * Stored rows NEVER contain pre-rendered text — only i18n keys + params.
 * Rendering happens client-side at read time via react-i18next.
 */
import type { Db } from '../client'
import { insertNotification } from './communications'

export interface CreateNotificationInput {
  tenantId: string
  userId: string
  type: string
  titleKey: string
  bodyKey?: string
  params?: Record<string, unknown>
  entityType?: string
  entityId?: string
}

/**
 * Create an in-app notification.
 *
 * The `pushWS` and `deliver` arguments are injected by the caller (route handler
 * or queue consumer) to avoid circular-package deps. Route files supply the
 * @zync/notifications implementations; this db query module stays dep-free.
 */
export async function createNotification(
  db: Db,
  input: CreateNotificationInput,
  opts?: {
    pushWS?: (userId: string, tenantId: string, type: string) => Promise<void>
    deliver?: (userId: string, type: string, title: string, body: string) => void
  },
): Promise<{ id: string }> {
  const result = await insertNotification(db, input)

  // Best-effort WebSocket push (synchronous — KV lookup only)
  if (opts?.pushWS) {
    opts.pushWS(input.userId, input.tenantId, input.type).catch(() => {
      // Degrade silently — client polls every 30s
    })
  }

  // Fire-and-forget adapter fanout (email / telegram / push)
  if (opts?.deliver) {
    opts.deliver(input.userId, input.type, input.titleKey, input.bodyKey ?? '')
  }

  return result
}
