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') ??
    'http://localhost:4003/api';

  const tradingApiUrl =
    readEnv(`${surfacePrefix}TRADING_API_URL`) ??
    readEnv('VITE_TRADING_API_URL') ??
    readEnv('TRADING_API_URL') ??
    `http://localhost:${productConfig.backendPort}/api`;

  return {
    productId,
    platformApiUrl,
    tradingApiUrl,
  };
}

