/**
 * Push Notifications Service
 * Handles sending push notifications via Pusher Beams
 * Also creates in-app notifications using harmonic-saas notification system
 */

import PushNotifications from '@pusher/push-notifications-server'
import { sendNotification as sendInAppNotification } from '../utils/notifications'

// Initialize Pusher Beams client
let beamsClient: PushNotifications | null = null

function getBeamsClient(): PushNotifications {
  if (!beamsClient) {
    const config = useRuntimeConfig()
    const instanceId = config.pusherBeamsInstanceId as string
    const secretKey = config.pusherBeamsSecretKey as string

    if (!instanceId || !secretKey) {
      throw new Error('Pusher Beams credentials not configured')
    }

    beamsClient = new PushNotifications({
      instanceId,
      secretKey
    })
  }

  return beamsClient
}

export interface PushNotificationPayload {
  title: string
  body: string
  data?: Record<string, string>
  deepLink?: string
  /** If true, also create an in-app notification (default: true) */
  createInAppNotification?: boolean
  /** Sender name for in-app notification */
  senderName?: string
}

/**
 * Send push notification to a specific user
 * Uses Pusher Beams "Authenticated Users" feature
 * Also creates an in-app notification by default
 */
export async function sendPushNotificationToUser(
  userId: string,
  notification: PushNotificationPayload
): Promise<{ publishId: string } | null> {
  // Check if push notifications are configured
  if (!isBeamsConfigured()) {
    console.warn('[Push] Pusher Beams not configured, skipping push notification')
    // Still create in-app notification if requested
    if (notification.createInAppNotification !== false) {
      await createInAppNotification(userId, notification)
    }
    return null
  }

  const client = getBeamsClient()

  // Default deep link to notifications page
  const deepLink = notification.deepLink || '/dashboard/account/notifications'

  // Use both notification and data payloads
  // The notification payload ensures delivery even when app is killed
  // The data payload contains the deep link for navigation
  const response = await client.publishToUsers([userId], {
    fcm: {
      notification: {
        title: notification.title,
        body: notification.body
      },
      data: {
        ...notification.data,
        deepLink,
        // Also include title/body in data for MyFirebaseMessagingService when app is in foreground
        title: notification.title,
        body: notification.body
      }
    },
    // APNs config for iOS (for future use)
    apns: {
      aps: {
        alert: {
          title: notification.title,
          body: notification.body
        }
      },
      data: {
        ...notification.data,
        deepLink
      }
    }
  })

  // Create in-app notification (default: true)
  if (notification.createInAppNotification !== false) {
    await createInAppNotification(userId, notification)
  }

  return { publishId: response.publishId }
}

/**
 * Send push notification to multiple users
 * Also creates in-app notifications by default
 */
export async function sendPushNotificationToUsers(
  userIds: string[],
  notification: PushNotificationPayload
): Promise<{ publishId: string } | null> {
  if (userIds.length === 0) {
    throw new Error('No users specified')
  }

  // Pusher Beams has a limit of 1000 users per request
  if (userIds.length > 1000) {
    throw new Error('Cannot send to more than 1000 users at once')
  }

  // Check if push notifications are configured
  if (!isBeamsConfigured()) {
    console.warn('[Push] Pusher Beams not configured, skipping push notification')
    // Still create in-app notifications if requested
    if (notification.createInAppNotification !== false) {
      await Promise.allSettled(
        userIds.map(userId => createInAppNotification(userId, notification))
      )
    }
    return null
  }

  const client = getBeamsClient()

  // Default deep link to notifications page
  const deepLink = notification.deepLink || '/dashboard/account/notifications'

  // Use both notification and data payloads
  const response = await client.publishToUsers(userIds, {
    fcm: {
      notification: {
        title: notification.title,
        body: notification.body
      },
      data: {
        ...notification.data,
        deepLink,
        title: notification.title,
        body: notification.body
      }
    },
    apns: {
      aps: {
        alert: {
          title: notification.title,
          body: notification.body
        }
      },
      data: {
        ...notification.data,
        deepLink
      }
    }
  })

  // Create in-app notifications for all users (default: true)
  if (notification.createInAppNotification !== false) {
    await Promise.allSettled(
      userIds.map(userId => createInAppNotification(userId, notification))
    )
  }

  return { publishId: response.publishId }
}

/**
 * Helper to create in-app notification
 */
async function createInAppNotification(
  userId: string,
  notification: PushNotificationPayload
): Promise<void> {
  try {
    const deepLink = notification.deepLink || '/dashboard/account/notifications'
    await sendInAppNotification({
      userId,
      senderName: notification.senderName || notification.title,
      body: notification.body,
      url: deepLink
    })
    console.log('[Push] Created in-app notification for user:', userId)
  } catch (error) {
    // Don't fail push notification if in-app notification fails
    console.error('[Push] Failed to create in-app notification:', error)
  }
}

/**
 * Generate Beams auth token for a user
 * Used by client to authenticate with Pusher Beams
 */
export function generateBeamsToken(userId: string): { token: string } {
  const client = getBeamsClient()
  const beamsToken = client.generateToken(userId)
  return beamsToken
}

/**
 * Delete user from Pusher Beams
 * Call this when user logs out or deletes account
 */
export async function deleteUserFromBeams(userId: string): Promise<void> {
  if (!isBeamsConfigured()) {
    return
  }
  const client = getBeamsClient()
  await client.deleteUser(userId)
}

/**
 * Check if Pusher Beams is configured
 */
export function isBeamsConfigured(): boolean {
  const config = useRuntimeConfig()
  return !!(config.pusherBeamsInstanceId && config.pusherBeamsSecretKey)
}
