import { productConfig } from './product.js';

export type ProductSurface = 'web' | 'mobile' | 'backend';

export interface RuntimeEnvironment {
  productId: string;
  platformApiUrl: string;
  tradingApiUrl: string;
}

function readEnv(key: string): string | undefined {
  const value = typeof process !== 'undefined' ? process.env[key] : undefined;
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
}

export function getRuntimeEnvironment(surface: ProductSurface): RuntimeEnvironment {
  const surfacePrefix =
    surface === 'mobile' ? 'EXPO_PUBLIC_' : surface === 'web' ? 'NEXT_PUBLIC_' : '';

  const productId =
    readEnv(`${surfacePrefix}PRODUCT_ID`) ??
    readEnv('VITE_PRODUCT_ID') ??
    readEnv('PRODUCT_ID') ??
    productConfig.productId;

  const platformApiUrl =
    readEnv(`${surfacePrefix}PLATFORM_URL`) ??
    readEnv('VITE_PLATFORM_URL') ??
    readEnv('PLATFORM_API_URL') ??
    (surface === 'web' ? 'https://api.bytelyst.com/platform/api' : 'http://localhost:4003/api');

  // Web code appends /api/... itself — no /api suffix in the base URL.
  // Mobile code expects /api included and strips it for socket (EXPO_PUBLIC_TRADING_API_URL=http://host:port/api).
  // Always set the surface-specific env var explicitly; do not rely on this default for mobile.
  const tradingApiUrl =
    readEnv(`${surfacePrefix}TRADING_API_URL`) ??
    readEnv('VITE_TRADING_API_URL') ??
    readEnv('TRADING_API_URL') ??
    (surface === 'web'
      ? 'https://api.bytelyst.com/invttrdg'
      : `http://localhost:${productConfig.backendPort}`);

  return {
    productId,
    platformApiUrl,
    tradingApiUrl,
  };
}
