import { CoinMarketCapClient } from '../../../infrastructure/external/coinmarketcap-client';

export interface TokenPrice {
  readonly price: number;
  readonly change24h: number;
  readonly mcap: number;
}

export class GetTokenPricesUseCase {
  constructor(private readonly coinMarketCapClient: CoinMarketCapClient) {}

  async execute(symbols: string[]): Promise<Record<string, TokenPrice>> {
    if (symbols.length === 0) {
      return {};
    }

    const all = await this.coinMarketCapClient.getCoinMap();
    const idsBySymbol = new Map<string, number>();

    for (const symbol of symbols) {
      const upperSymbol = symbol.toUpperCase();
      if (idsBySymbol.has(upperSymbol)) {
        continue;
      }

      const matches = all
        .filter(
          (entry) =>
            entry.symbol.toUpperCase() === upperSymbol && entry.rank !== null,
        )
        .sort((a, b) => (a.rank ?? Infinity) - (b.rank ?? Infinity));

      if (matches.length === 0) {
        continue;
      }

      idsBySymbol.set(upperSymbol, matches[0].id);
    }

    const ids = Array.from(idsBySymbol.values());
    if (ids.length === 0) {
      return {};
    }

    const quotes = await this.coinMarketCapClient.getTokenQuotes(ids);

    const result: Record<string, TokenPrice> = {};
    for (const [symbol, id] of idsBySymbol.entries()) {
      const quote = quotes.get(id);
      if (quote) {
        result[symbol] = {
          price: quote.price,
          change24h: quote.change24h,
          mcap: quote.marketCap,
        };
      }
    }

    return result;
  }
}
