/**
 * FXCM FxPriceProvider adapter (traditional forex)
 * Uses FXCM REST API - requires API credentials
 * Docs: https://fxcm.github.io/rest-api-docs
 */

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

const FXCM_API = 'https://api-demo.fxcm.com';

const SYMBOL_MAP: Record<string, string> = {
  'EUR/USD': 'EUR/USD',
  'USD/JPY': 'USD/JPY',
  'GBP/USD': 'GBP/USD',
  'USD/CHF': 'USD/CHF',
  'AUD/USD': 'AUD/USD',
};

export class FxcmPriceAdapter implements FxPriceProvider {
  private token: string;
  private baseUrl: string;
  private cache: Map<string, { price: string; ts: number }> = new Map();
  private cacheTtlMs = 10 * 1000;

  constructor(config: { token: string; baseUrl?: string }) {
    this.token = config.token;
    this.baseUrl = config.baseUrl ?? FXCM_API;
  }

  async getPrice(pair: string, _amount?: number): Promise<string | null> {
    const cached = this.cache.get(pair);
    if (cached && Date.now() - cached.ts < this.cacheTtlMs) return cached.price;

    const symbol = SYMBOL_MAP[pair] ?? pair.replace('/', '/');
    try {
      const res = await fetch(`${this.baseUrl}/candles/1/m1?symbols=${symbol}&count=1`, {
        headers: { Authorization: `Bearer ${this.token}` },
      });
      if (!res.ok) return null;
      const data = (await res.json()) as { candles?: Array<{ bid?: number; ask?: number }> };
      const candle = data.candles?.[0];
      const price =
        candle?.bid && candle?.ask
          ? ((candle.bid + candle.ask) / 2).toFixed(8)
          : candle?.bid
          ? String(candle.bid)
          : null;
      if (price) {
        this.cache.set(pair, { price, ts: Date.now() });
        return price;
      }
    } catch {
      if (cached) return cached.price;
    }
    return null;
  }

  isPairSupported(pair: string): boolean {
    return pair in SYMBOL_MAP || (pair.includes('/') && pair.length >= 7);
  }
}
