import { createWebTelemetry } from '@bytelyst/telemetry-client';
import { createRNPlatformSDK } from '@bytelyst/react-native-platform-sdk';
import { getRuntimeEnvironment } from './runtime.js';
import { productConfig } from './product.js';
import { createRequestId } from './request-id.js';

interface TradingKillSwitchResult {
  disabled: boolean;
  message: string | null;
}

function createRepoKillSwitchClient(baseUrl: string, productId: string, platform: 'web' | 'mobile') {
  return {
    async check(): Promise<TradingKillSwitchResult> {
      try {
        const response = await globalThis.fetch(
          `${baseUrl}/settings/kill-switch?platform=${encodeURIComponent(platform)}`,
          {
            headers: {
              'x-product-id': productId,
              'x-request-id': createRequestId('kill-switch'),
            },
          }
        );

        if (!response.ok) return { disabled: false, message: null };

        const data = await response.json() as { disabled?: boolean; message?: string | null };
        return {
          disabled: data.disabled ?? false,
          message: data.message ?? null,
        };
      } catch {
        return { disabled: false, message: null };
      }
    },
  };
}

export function createTradingKillSwitchClient(platform: 'web' | 'mobile') {
  const runtime = getRuntimeEnvironment(platform);
  return createRepoKillSwitchClient(runtime.platformApiUrl, runtime.productId, platform);
}

export function createTradingWebTelemetry() {
  const runtime = getRuntimeEnvironment('web');
  return createWebTelemetry({
    productId: runtime.productId,
    channel: 'invttrdg_web',
    baseUrl: runtime.platformApiUrl,
    appVersion: productConfig.version,
    releaseChannel: process.env.NODE_ENV === 'production' ? 'prod' : 'dev',
  });
}

export function createTradingMobileSdk(getAccessToken: () => string | null) {
  const runtime = getRuntimeEnvironment('mobile');
  return createRNPlatformSDK({
    baseURL: runtime.platformApiUrl,
    productId: runtime.productId,
    getAccessToken,
  });
}
