/**
 * Plugin to handle magic link deep links in Capacitor
 *
 * When a user clicks a magic link in their email, Android App Links
 * will open the app with the verification URL. This plugin:
 * 1. Detects when the app is opened with a magic link URL
 * 2. Navigates to the verification URL in a hidden iframe
 * 3. Extracts the session cookie from the WebView
 * 4. Redirects to dashboard
 */
import { App } from '@capacitor/app'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default defineNuxtPlugin((_nuxtApp: any) => {
  // Only run in actual Capacitor environment, not during SSG
  if (typeof window === 'undefined') return

  // Only run in Capacitor
  const apiBaseUrl = useApiBaseUrl()
  if (!apiBaseUrl) return

  const log = useLogger('Magic Link Handler')
  log.info('Plugin initialized')

  // Track processed URLs to prevent loops
  const processedUrls = new Set<string>()

  // Get composables in plugin context (outside event listener)
  const router = useRouter()
  const localePath = useLocalePath()

  // Listen for app URL opens (deep links)
  App.addListener('appUrlOpen', async (data) => {
    log.info('App opened with URL:', data.url)

    // Prevent processing the same URL twice (avoid loops)
    if (processedUrls.has(data.url)) {
      log.info('URL already processed, ignoring')
      return
    }

    const url = new URL(data.url)

    // Check if this is the App Link to open magic link
    if (url.pathname.includes('/app/open-magic-link')) {
      log.info('Open magic link App Link detected')

      // Mark as processed
      processedUrls.add(data.url)

      try {
        // Parse the URL to get the actual verification URL
        const verificationUrl = url.searchParams.get('url')

        if (!verificationUrl) {
          log.error('No verification URL in App Link')
          await router.push(localePath('/auth'))
          return
        }

        log.info('Verification URL:', verificationUrl)

        // Update the callback URL to point to our backend callback page
        const finalUrl = new URL(verificationUrl)
        finalUrl.searchParams.set('callbackURL', `${apiBaseUrl}/auth/magic-link-callback`)

        log.info('Navigating WebView to:', finalUrl.toString())

        // Navigate the WebView to the verification URL so cookies are set in the WebView jar
        window.location.href = finalUrl.toString()
      } catch (error) {
        log.error('Error processing App Link:', error)
        await router.push(localePath('/auth'))
      }

      return
    }

    // Check if this is a return from magic link verification (via App Link)
    if (url.pathname.includes('/app/return-from-magic-link')) {
      log.info('Return from magic link verification App Link detected')

      // Mark as processed
      processedUrls.add(data.url)

      try {
        const token = url.searchParams.get('token')
        const inAppPath = localePath('/app/return-from-magic-link')
        const target = token ? `${inAppPath}?token=${encodeURIComponent(token)}` : inAppPath
        log.info('Routing to in-app return page:', target)
        await router.push(target)
      } catch (error) {
        log.error('Error routing to return page:', error)
        await router.push(localePath('/auth'))
      }
    }
  })
})
