import { Capacitor } from '@capacitor/core'

/**
 * Composable for Capacitor-specific functionality
 *
 * Provides utilities for detecting Capacitor environment and managing
 * authentication tokens that are required for cross-origin API calls.
 */
export function useCapacitor() {
  const config = useRuntimeConfig()

  // Use Capacitor.isNativePlatform() for reliable detection
  // This works even before plugins run
  const isCapacitorNative = import.meta.client ? Capacitor.isNativePlatform() : false

  // Get baseURL from config (set by plugin) or fallback for Capacitor
  const backendApiBaseUrl = config.public.backendApiBaseUrl as string | undefined

  // Only use baseURL for cross-origin requests when:
  // 1. We're actually in a Capacitor native app, OR
  // 2. We're explicitly configured for cross-origin mode (backendApiBaseUrl set AND not same as current origin)
  const isCapacitor = computed(() => {
    // If we're in a native Capacitor platform, we're definitely Capacitor
    if (isCapacitorNative) return true

    // On the web, only use cross-origin mode if backendApiBaseUrl is set
    // AND it's different from the current origin (i.e., not localhost pointing to localhost)
    if (backendApiBaseUrl && import.meta.client) {
      const currentOrigin = window.location.origin
      // If the backend URL starts with the current origin, we're same-origin
      if (backendApiBaseUrl.startsWith(currentOrigin)) return false
      // If both are localhost (even different ports), treat as same-origin for dev
      if (currentOrigin.includes('localhost') && backendApiBaseUrl.includes('localhost')) return false
    }

    // Don't use cross-origin mode for regular web browsing
    return false
  })

  /**
   * Get the authentication token from localStorage (Capacitor only)
   * Returns null if not in Capacitor environment or token not found
   */
  const getAuthToken = (): string | null => {
    if (!isCapacitor.value) return null
    return typeof localStorage !== 'undefined'
      ? localStorage.getItem('better-auth-token')
      : null
  }

  /**
   * Set the authentication token in localStorage (Capacitor only)
   * No-op if not in Capacitor environment
   */
  const setAuthToken = (token: string): void => {
    if (!isCapacitor.value) return
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem('better-auth-token', token)
    }
  }

  /**
   * Clear the authentication token from localStorage (Capacitor only)
   * No-op if not in Capacitor environment
   */
  const clearAuthToken = (): void => {
    if (!isCapacitor.value) return
    if (typeof localStorage !== 'undefined') {
      localStorage.removeItem('better-auth-token')
    }
  }

  /**
   * Extract token from various response formats
   * Used when Better Auth returns tokens in different response structures
   */
  const extractTokenFromResponse = (response: unknown): string | null => {
    if (!response || typeof response !== 'object') return null

    const r = response as Record<string, unknown>

    // Try various possible token locations
    const data = r.data as Record<string, unknown> | undefined
    const session = data?.session as Record<string, unknown> | undefined
    const token = session?.token
      || data?.token
      || r.token
      || session?.sessionToken
      || (data && typeof data === 'object' && 'sessionToken' in data ? data.sessionToken : null)

    return typeof token === 'string' ? token : null
  }

  return {
    isCapacitor,
    baseURL: computed(() => {
      // Only return baseURL if we're in cross-origin/Capacitor mode
      if (isCapacitor.value && backendApiBaseUrl) return backendApiBaseUrl
      // Otherwise, empty string (web uses relative paths)
      return ''
    }),
    getAuthToken,
    setAuthToken,
    clearAuthToken,
    extractTokenFromResponse
  }
}
