/**
 * WebSocket push seam — system-communications-notifications (Task 9).
 *
 * Looks up `ws_session:{userId}:{tenantId}` in KV; if a DO id is present,
 * forwards the notification to the TenantRealtimeDO (owned by
 * tasks-detail-communication). Degrades silently when no session/DO is found.
 *
 * Clients fall back to 30s polling when no WebSocket session is active.
 * This function NEVER throws — it is always best-effort.
 */
import type { Env } from '@zync/types'

/**
 * Push a notification over WebSocket if the user has an active DO session.
 * No-op when the KV key is absent or the DO stub is unavailable.
 */
export async function pushOverWebSocket(
  userId: string,
  tenantId: string,
  notification: { type: string; titleKey: string; bodyKey?: string; params?: Record<string, unknown> },
  env: Env,
): Promise<void> {
  try {
    const kvKey = `ws_session:${userId}:${tenantId}`
    const doId = await env.KV.get(kvKey)
    if (!doId) return // No active WebSocket session → client polls

    // Forward to the TenantRealtimeDO (owned by tasks-detail-communication)
    const stub = env.DO_REALTIME.get(env.DO_REALTIME.idFromString(doId))
    await stub.fetch(
      new Request(`https://internal/push/${userId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'notification',
          payload: notification,
        }),
      }),
    )
  } catch {
    // Best-effort: never throw. Client polls every 30s as fallback.
  }
}
