import { createSuccessResponse } from '../utils/errors'

interface PublicConfigResponse {
  runtimeConfig: {
    harmonicSaaSVersion: string
    nuxtVersion: string
    betterAuthUrl: string
    auth: {
      redirectUserTo: string
      redirectGuestTo: string
    }
    backendApiBaseUrl: string
    pusherKey: string
    pusherCluster: string
  }
  environment: {
    nodeEnv: string
    isProduction: boolean
    isDevelopment: boolean
  }
  publicEnvVars: {
    NUXT_PUBLIC_BACKEND_API_BASE_URL?: string
    NUXT_PUBLIC_PUSHER_KEY?: string
    NUXT_PUBLIC_PUSHER_CLUSTER?: string
    NUXT_BETTER_AUTH_URL?: string
  }
}

export default defineCachedEventHandler(
  async (_event) => {
    const config = useRuntimeConfig()
    const nodeEnv = process.env.NODE_ENV || 'development'

    const response: PublicConfigResponse = {
      runtimeConfig: {
        harmonicSaaSVersion: config.public.harmonicSaaSVersion,
        nuxtVersion: config.public.nuxtVersion,
        betterAuthUrl: config.public.betterAuthUrl,
        auth: {
          redirectUserTo: config.public.auth.redirectUserTo,
          redirectGuestTo: config.public.auth.redirectGuestTo
        },
        backendApiBaseUrl: config.public.backendApiBaseUrl,
        pusherKey: config.public.pusherKey,
        pusherCluster: config.public.pusherCluster
      },
      environment: {
        nodeEnv,
        isProduction: nodeEnv === 'production',
        isDevelopment: nodeEnv === 'development'
      },
      publicEnvVars: {
        NUXT_PUBLIC_BACKEND_API_BASE_URL: process.env.NUXT_PUBLIC_BACKEND_API_BASE_URL,
        NUXT_PUBLIC_PUSHER_KEY: process.env.NUXT_PUBLIC_PUSHER_KEY,
        NUXT_PUBLIC_PUSHER_CLUSTER: process.env.NUXT_PUBLIC_PUSHER_CLUSTER,
        NUXT_BETTER_AUTH_URL: process.env.NUXT_BETTER_AUTH_URL
      }
    }

    return createSuccessResponse<PublicConfigResponse>(response)
  },
  {
    maxAge: 60 * 5 // Cache for 5 minutes
  }
)
