/**
 * Binance FxPriceProvider adapter
 */

import type { FxPriceProvider } from '@/core/fx/price-provider.interface';

const BINANCE_API = 'https://api.binance.com';

function toBinanceSymbol(pair: string): string {
  const normalized = pair.replace('/', '');
  if (pair.endsWith('/USD') || pair.endsWith('/USDT')) return normalized + 'USDT';
  return normalized;
}

export class BinancePriceAdapter implements FxPriceProvider {
  private cache = new Map<string, { price: string; ts: number }>();
  private cacheTtlMs = 30000;

  async getPrice(pair: string): Promise<string | null> {
    const cached = this.cache.get(pair);
    if (cached && Date.now() - cached.ts < this.cacheTtlMs) return cached.price;
    const symbol = toBinanceSymbol(pair);
    try {
      const res = await fetch(BINANCE_API + '/api/v3/ticker/price?symbol=' + symbol);
      if (!res.ok) return null;
      const data = (await res.json()) as { price?: string };
      if (data.price) {
        this.cache.set(pair, { price: data.price, ts: Date.now() });
        return data.price;
      }
    } catch {
      if (cached) return cached.price;
    }
    return null;
  }

  isPairSupported(pair: string): boolean {
    return toBinanceSymbol(pair).length >= 6;
  }
}
