/**
 * Unified notification utility
 *
 * This utility ensures all notifications are created in the database
 * and users are notified via Pusher in real-time.
 */

import { createNotification, getUnreadNotificationsCount, type CreateNotificationPayload, type NotificationRecord } from '../database/queries/notifications'
import { sendPusherEvent } from './pusher'

/**
 * Send a notification to a user
 *
 * This function:
 * 1. Creates the notification in the database
 * 2. Emits Pusher events to notify the user in real-time
 *
 * @param payload - The notification payload
 * @returns The created notification record
 */
export async function sendNotification(payload: CreateNotificationPayload): Promise<NotificationRecord> {
  // Create the notification in the database
  const notification = await createNotification(payload)

  // Emit real-time events to notify the user via Pusher
  try {
    const unreadCount = await getUnreadNotificationsCount(payload.userId)
    sendPusherEvent(payload.userId, 'notification:new', { notification })
    sendPusherEvent(payload.userId, 'notification:unread-count', { count: unreadCount })
  } catch (error) {
    // Don't fail the request if real-time emission fails
    // The notification was already created in the database
    console.error('[sendNotification] Failed to emit real-time events:', error)
  }

  return notification
}
