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 baseURL = config.public.backendApiBaseUrl as string | undefined
  const isCapacitor = computed(() => {
    // If we're in a native Capacitor platform, we're definitely Capacitor
    if (isCapacitorNative) return true
    // Otherwise, check if baseURL is set (for cases where plugin hasn't run yet)
    return !!baseURL
  })

  /**
   * 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(() => {
      // If baseURL is set, use it
      if (baseURL) return baseURL
      // Otherwise, empty string (web uses relative paths, Capacitor should have baseURL configured)
      return ''
    }),
    getAuthToken,
    setAuthToken,
    clearAuthToken,
    extractTokenFromResponse
  }
}
