/**
 * Kraken FxPriceProvider adapter
 */

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

const KRAKEN_API = 'https://api.kraken.com';

const PAIR_MAP: Record<string, string> = {
  'BTC/USD': 'XXBTZUSD',
  'ETH/USD': 'XETHZUSD',
  'ETH/BTC': 'XETHXXBT',
};

function toKrakenPair(pair: string): string {
  if (PAIR_MAP[pair]) return PAIR_MAP[pair];
  const [base, quote] = pair.split('/');
  const b = base === 'BTC' ? 'XXBT' : base === 'ETH' ? 'XETH' : base;
  const q = quote === 'USD' ? 'ZUSD' : quote === 'EUR' ? 'ZEUR' : quote;
  return b + q;
}

export class KrakenPriceAdapter 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 krakenPair = toKrakenPair(pair);
    try {
      const res = await fetch(KRAKEN_API + '/0/public/Ticker?pair=' + krakenPair);
      if (!res.ok) return null;
      const data = (await res.json()) as { result?: Record<string, { c?: string[] }> };
      const ticker = data.result?.[krakenPair] ?? Object.values(data.result ?? {})[0];
      const price = ticker?.c?.[0];
      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;
  }
}
