import { Capacitor } from '@capacitor/core'

/**
 * Plugin to set the API base URL for Capacitor apps
 * Pages should use useApiBaseUrl() composable to get the base URL
 *
 * For Capacitor builds, set NUXT_PUBLIC_BACKEND_API_BASE_URL in your .env
 * to point to your production backend (e.g., https://your-app.vercel.app)
 */
export default defineNuxtPlugin({
  name: 'api-base-url',
  setup() {
    const isCapacitor = Capacitor.isNativePlatform()
    const config = useRuntimeConfig()
    const log = useLogger('Capacitor')

    if (isCapacitor) {
      // In Capacitor, use the base URL from the build-time config
      const baseURL = config.public.backendApiBaseUrl
      if (!baseURL) {
        log.warn(
          'NUXT_PUBLIC_BACKEND_API_BASE_URL is not set. '
          + 'Capacitor apps require this to be set to your production backend URL. '
          + 'API calls will fail without it.'
        )
      }
      config.public.backendApiBaseUrl = baseURL || ''
    } else {
      // On web, we don't need a base URL (use relative paths)
      config.public.backendApiBaseUrl = ''
    }
  }
})
