/**
 * Application configuration with type-safe access to environment variables.
 *
 * All VITE_* environment variables are exposed at build time via import.meta.env.
 * This module provides a typed interface and runtime validation.
 */

interface AppConfig {
  /** Backend API base URL (e.g., http://localhost:8000) */
  apiBaseUrl: string
  /** WebSocket server URL for Socket.IO (e.g., http://localhost:8000) */
  wsUrl: string
  /** OAuth redirect URI after authentication (e.g., http://localhost:5173/auth/callback) */
  oauthRedirectUri: string
  /** Whether running in development mode */
  isDev: boolean
  /** Whether running in production mode */
  isProd: boolean
}

function getEnvVar(key: string, fallback?: string): string {
  const value = import.meta.env[key] as string | undefined
  if (value === undefined || value === '') {
    if (fallback !== undefined) {
      return fallback
    }
    throw new Error(`Missing required environment variable: ${key}`)
  }
  return value
}

/**
 * Application configuration object.
 *
 * Values are read from environment variables at build time.
 * In development, these come from .env.development.
 * In production, these come from .env.production.
 */
export const config: AppConfig = {
  apiBaseUrl: getEnvVar('VITE_API_BASE_URL', 'http://localhost:8000'),
  wsUrl: getEnvVar('VITE_WS_URL', 'http://localhost:8000'),
  oauthRedirectUri: getEnvVar('VITE_OAUTH_REDIRECT_URI', 'http://localhost:5173/auth/callback'),
  isDev: import.meta.env.DEV,
  isProd: import.meta.env.PROD,
}

/**
 * Build the full API URL for an endpoint.
 *
 * @param path - API path (e.g., '/api/users/me')
 * @returns Full URL (e.g., 'http://localhost:8000/api/users/me')
 */
export function apiUrl(path: string): string {
  const base = config.apiBaseUrl.replace(/\/$/, '')
  const cleanPath = path.startsWith('/') ? path : `/${path}`
  return `${base}${cleanPath}`
}

export default config
