import type { RuntimeConfig } from 'nuxt/schema'

/**
 * Auth configuration interface
 */
export interface AuthConfig {
  secret: string
  baseURL: string
  trustedOrigins: string[]
  plugins: {
    bearer: boolean
    passkey: boolean
    magicLink: boolean
    organization: boolean
  }
  socialProviders: {
    github?: {
      clientId: string
      clientSecret: string
    }
    google?: {
      clientId: string
      clientSecret: string
    }
  }
  isProduction: boolean
}

/**
 * Resolve the base URL for Better Auth
 * Priority: 1. Server env var (NUXT_BETTER_AUTH_URL), 2. Public env var (NUXT_PUBLIC_BETTER_AUTH_URL),
 *           3. Vercel auto-detect, 4. Localhost fallback
 */
function resolveBaseURL(config: RuntimeConfig): string {
  const serverUrl = config.betterAuthUrl as string | undefined
  const publicUrl = config.public.betterAuthUrl as string | undefined

  if (serverUrl) return serverUrl
  if (publicUrl) return publicUrl

  // Auto-detect Vercel deployment URL
  const vercelUrl = process.env.VERCEL_URL
  if (vercelUrl) {
    return `https://${vercelUrl}`
  }

  return 'http://localhost:3000'
}

/**
 * Get list of trusted origins for Better Auth
 */
function getTrustedOrigins(config: RuntimeConfig): string[] {
  const baseURL = resolveBaseURL(config)

  return [
    baseURL, // Always trust the base URL (from env vars or auto-detected)
    'https://localhost', // Capacitor Android WebView
    'http://localhost', // Capacitor Android WebView (fallback)
    'http://localhost:3000', // Local dev server
    'capacitor://localhost', // Capacitor iOS
    'ionic://localhost' // Ionic
  ]
}

/**
 * Get enabled plugins configuration
 */
function getEnabledPlugins(config: RuntimeConfig): AuthConfig['plugins'] {
  return {
    bearer: true,
    passkey: true,
    magicLink: config.public.saas?.enableMagicLink ?? false,
    organization: config.public.saas?.enableOrganizations ?? false
  }
}

/**
 * Get social providers configuration
 */
function getSocialProviders(config: RuntimeConfig): AuthConfig['socialProviders'] {
  return {
    github: config.githubClientId && config.githubClientSecret
      ? {
          clientId: config.githubClientId as string,
          clientSecret: config.githubClientSecret as string
        }
      : undefined,
    google: config.googleClientId && config.googleClientSecret
      ? {
          clientId: config.googleClientId as string,
          clientSecret: config.googleClientSecret as string
        }
      : undefined
  }
}

/**
 * Get complete auth configuration
 * Centralizes all Better Auth configuration logic
 */
export function getAuthConfig(): AuthConfig {
  const config = useRuntimeConfig()

  return {
    secret: config.betterAuthSecret || process.env.NUXT_BETTER_AUTH_SECRET || 'build-time-secret-not-for-production',
    baseURL: resolveBaseURL(config),
    trustedOrigins: getTrustedOrigins(config),
    plugins: getEnabledPlugins(config),
    socialProviders: getSocialProviders(config),
    isProduction: process.env.NODE_ENV === 'production'
  }
}
