/**
 * Cliente de preço SPOT público da Binance (mercado, SEM assinatura).
 * Usado pela trava de spot do pricing. É separado do cliente C2C de
 * propósito: não leva apiKey/secret nem headers de C2C.
 *
 * Endpoint: GET /api/v3/ticker/price?symbol=USDTBRL
 */

const BASE = "https://api.binance.com";

export interface SpotTicker {
  symbol: string;
  price: string; // DECIMAL como string
}

export async function getSpotPrice(symbol: string): Promise<string> {
  const url = `${BASE}/api/v3/ticker/price?symbol=${encodeURIComponent(symbol)}`;
  const res = await fetch(url);
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(`Spot ${symbol}: HTTP ${res.status} ${text}`);
  }
  const data = (await res.json()) as Partial<SpotTicker>;
  if (!data || typeof data.price !== "string") {
    throw new Error(`Spot ${symbol}: resposta inesperada.`);
  }
  return data.price;
}

/** Busca vários símbolos de uma vez (uma chamada por símbolo, em paralelo). */
export async function getSpotPrices(symbols: string[]): Promise<Map<string, string>> {
  const out = new Map<string, string>();
  await Promise.all(
    symbols.map(async (s) => {
      try {
        out.set(s, await getSpotPrice(s));
      } catch {
        // Símbolo sem par spot 1:1 — fica de fora; a trava cai no fallback.
      }
    }),
  );
  return out;
}
