/**
 * Pusher Beams client plugin
 * Initializes Pusher Beams for push notifications on native platforms
 * and handles user authentication lifecycle
 *
 * This plugin only runs when:
 * - enablePushNotifications is true in saas config
 * - Running on a native Capacitor platform
 * - pusherBeamsInstanceId is configured
 */

import { usePusherBeams } from '../composables/usePusherBeams'

export default defineNuxtPlugin({
  name: 'pusher-beams',
  enforce: 'post',
  setup() {
    // Only run on client-side
    if (!import.meta.client) return

    // Use onNuxtReady to ensure all composables are available
    onNuxtReady(async () => {
      const log = useLogger('PusherBeams Plugin')

      try {
        const config = useRuntimeConfig()

        // Check if push notifications are enabled in saas config
        const saasConfig = config.public.saas as { enablePushNotifications?: boolean } | undefined
        if (!saasConfig?.enablePushNotifications) {
          log.info('Push notifications not enabled in saas config, skipping')
          return
        }

        // Check if useCapacitor is available
        let isCapacitorValue = false
        try {
          const capacitor = useCapacitor()
          isCapacitorValue = capacitor?.isCapacitor?.value === true
        } catch {
          log.info('useCapacitor not available')
          return
        }

        if (!isCapacitorValue) {
          log.info('Not on native platform, skipping')
          return
        }

        const instanceId = config.public.pusherBeamsInstanceId as string
        if (!instanceId) {
          log.info('No instance ID configured, skipping')
          return
        }

        const { user } = useAuth()
        const pusherBeams = usePusherBeams()

        // Initialize Pusher Beams
        const initializeBeams = async () => {
          const success = await pusherBeams.initialize(instanceId)
          if (success) {
            log.info('Initialized successfully')
          }
        }

        // Associate user with Pusher Beams after login
        const setupUserBeams = async (userId: string) => {
          if (!pusherBeams.isInitialized.value) {
            await initializeBeams()
          }
          const success = await pusherBeams.setUser(userId)
          if (success) {
            log.info('User associated:', userId)
          }
        }

        // Clear Pusher Beams state on logout
        const clearUserBeams = async () => {
          await pusherBeams.clearState()
          log.info('User cleared')
        }

        // Watch for user changes
        watch(
          () => user.value,
          async (newUser, oldUser) => {
            if (newUser?.id && newUser.id !== oldUser?.id) {
              await setupUserBeams(newUser.id)
            } else if (!newUser && oldUser) {
              await clearUserBeams()
            }
          },
          { immediate: true }
        )
      } catch (error) {
        const log = useLogger('PusherBeams Plugin')
        log.error('Error during setup:', error)
      }
    })
  }
})
