/**
 * Pusher integration for real-time notifications on Vercel
 *
 * Pusher provides WebSocket support that works with serverless architectures.
 * Free tier: 200k messages/day, 100 concurrent connections
 */

import Pusher from 'pusher'

let pusherInstance: Pusher | null = null

function getPusher(): Pusher | null {
  if (pusherInstance) {
    return pusherInstance
  }

  const appId = process.env.PUSHER_APP_ID
  const key = process.env.PUSHER_KEY
  const secret = process.env.PUSHER_SECRET
  const cluster = process.env.PUSHER_CLUSTER || 'eu'

  if (!appId || !key || !secret) {
    console.warn('[Pusher] Missing environment variables. Set PUSHER_APP_ID, PUSHER_KEY, and PUSHER_SECRET to enable real-time notifications.')
    return null
  }

  pusherInstance = new Pusher({
    appId,
    key,
    secret,
    cluster,
    useTLS: true
  })

  return pusherInstance
}

/**
 * Send a real-time event to a specific user via Pusher
 */
export function sendPusherEvent(userId: string, event: string, data: unknown) {
  const pusher = getPusher()
  if (!pusher) {
    return
  }

  try {
    pusher.trigger(`private-user-${userId}`, event, data)
  } catch (error) {
    console.error('[Pusher] Failed to send event:', error)
  }
}

/**
 * Send a real-time event to all users via Pusher
 */
export function sendPusherEventToAll(event: string, data: unknown) {
  const pusher = getPusher()
  if (!pusher) {
    return
  }

  try {
    pusher.trigger('broadcast', event, data)
  } catch (error) {
    console.error('[Pusher] Failed to send broadcast event:', error)
  }
}
