import {
  enrichLeafUsdFields,
  fetchAllTokenTransfersForTx,
  type TokenTransferSummary,
  type UsdPricingConfig,
} from '@dbis/checkpoint-core';
import type { LeafRecord } from './tokenEnrich';

export async function enrichLeafUsdRecord(
  leaf: LeafRecord,
  cfg: UsdPricingConfig & {
    blockscoutApi: string;
    preloadedErc20?: TokenTransferSummary[];
  }
): Promise<LeafRecord> {
  if (cfg.enabled === false) return leaf;
  if (leaf.usdEnrichedAt && leaf.transfers != null && leaf.valueUsd != null) {
    return leaf;
  }

  const allErc20 =
    cfg.preloadedErc20 ??
    (await fetchAllTokenTransfersForTx(cfg.blockscoutApi, String(leaf.txHash)));
  return (await enrichLeafUsdFields(cfg, leaf, allErc20)) as LeafRecord;
}
