/**
 * Oanda FxPriceProvider adapter (traditional forex)
 * Uses Oanda v20 REST API - requires API key
 */

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

function toOandaInstrument(pair: string): string {
  return pair.replace('/', '_');
}

export class OandaPriceAdapter implements FxPriceProvider {
  private apiKey: string;
  private accountId: string;
  private baseUrl: string;
  private cache = new Map<string, { price: string; ts: number }>();
  private cacheTtlMs = 10000;

  constructor(config: { apiKey: string; accountId: string; environment?: 'practice' | 'live' }) {
    this.apiKey = config.apiKey;
    this.accountId = config.accountId;
    this.baseUrl =
      config.environment === 'live'
        ? 'https://api-fxtrade.oanda.com'
        : 'https://api-fxpractice.oanda.com';
  }

  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 instrument = toOandaInstrument(pair);
    try {
      const url = `${this.baseUrl}/v3/accounts/${this.accountId}/pricing?instruments=${instrument}`;
      const res = await fetch(url, { headers: { Authorization: `Bearer ${this.apiKey}` } });
      if (!res.ok) return null;
      const data = (await res.json()) as {
        prices?: Array<{ bids?: Array<{ price?: string }>; asks?: Array<{ price?: string }> }>;
      };
      const priceObj = data.prices?.[0];
      const bid = priceObj?.bids?.[0]?.price;
      const ask = priceObj?.asks?.[0]?.price;
      const price = bid && ask ? ((parseFloat(bid) + parseFloat(ask)) / 2).toFixed(8) : bid ?? ask;
      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.includes('/') && pair.length >= 7;
  }
}
