/**
 * Environment variable helper that works with window.configs system for production
 */
import logger from "@racletteCore/lib/logger"
declare global {
  interface Window {
    configs?: {
      RACLETTE_DEBUG_MODE?: string
      RACLETTE_SERVER_BASE_URL?: string
      RACLETTE_SOCKET_URL?: string
      [key: string]: string | undefined
    }
  }
}

const getEnvVariable = (name: string): string => {
  // First check runtime injected config (production)
  if (window.configs && window.configs[name] !== undefined) {
    const value = window.configs[name]
    return value
  }

  // Fallback to Vite build-time variables (development)
  if (typeof import.meta !== "undefined" && import.meta.env) {
    const buildTimeValue = import.meta.env[name]
    if (buildTimeValue !== undefined) {
      return buildTimeValue
    }
  }

  // Final defaults
  const defaults: Record<string, string> = {
    RACLETTE_SERVER_BASE_URL: "/api",
    RACLETTE_SOCKET_URL:
      typeof window !== "undefined" ? window.location.origin : "",
    RACLETTE_DEBUG_MODE: "false",
  }

  if (defaults[name]) {
    return defaults[name]
  }

  logger.error(
    `❌ Environment variable ${name} is not defined and has no default value`,
  )

  return ""
}

export default getEnvVariable
