// apps/web/src/server/notifications/push-fallback.ts
import { EVENT_REGISTRY, type NotifEvent } from './event-registry.js';
import { sendToUser } from '@/server/push/send.js';
import type { DrizzleClient } from '@/server/db/client.js';
import type { PushEnv } from '@/server/push/send.js';

/**
 * Send a Web Push notification as a fallback when the user has no live
 * WebSocket session. Only fires for events with `pushFallback: true` in
 * EVENT_REGISTRY.
 *
 * Delegates to the existing VAPID push module (`server/push/send.ts`).
 */
export async function sendPushFallback(args: {
  userId: string;
  event: NotifEvent;
  title: { he: string; en: string };
  body: { he: string | null; en: string | null };
  link?: string;
  db: DrizzleClient;
  env: PushEnv;
  /** Test hook — override the dispatch function. */
  _sendPush?: typeof sendToUser;
}): Promise<void> {
  const meta = EVENT_REGISTRY[args.event];
  if (!meta.pushFallback) return;

  const dispatch = args._sendPush ?? sendToUser;
  await dispatch(args.db, args.env, args.userId, {
    title: args.title.he,
    body: args.body.he ?? '',
    url: args.link ?? '/',
    tag: args.event,
    data: { titleEn: args.title.en, bodyEn: args.body.en ?? '', event: args.event },
  });
}
