import { TokenRepository, Token } from '../database/repositories/token-repo';
import { getCanonicalTokenByAddress } from '../config/canonical-tokens';

export interface ResolvedTokenDisplay {
  address: string;
  symbol: string;
  name: string;
  decimals?: number;
  source: 'db' | 'canonical' | 'fallback';
  token?: Token;
}

function shortenAddress(address: string): string {
  const lower = address.toLowerCase();
  return `${lower.slice(0, 6)}...${lower.slice(-4)}`;
}

export async function resolveTokenDisplay(
  tokenRepo: TokenRepository,
  chainId: number,
  address: string
): Promise<ResolvedTokenDisplay> {
  const normalized = address.toLowerCase();
  const [dbToken, canonicalToken] = await Promise.all([
    tokenRepo.getToken(chainId, normalized).catch(() => null),
    Promise.resolve(getCanonicalTokenByAddress(chainId, normalized)),
  ]);

  if (dbToken) {
    return {
      address: normalized,
      symbol: dbToken.symbol || canonicalToken?.symbol || shortenAddress(normalized),
      name: dbToken.name || canonicalToken?.name || dbToken.symbol || shortenAddress(normalized),
      decimals: dbToken.decimals ?? canonicalToken?.decimals,
      source: 'db',
      token: dbToken,
    };
  }

  if (canonicalToken) {
    return {
      address: normalized,
      symbol: canonicalToken.symbol,
      name: canonicalToken.name,
      decimals: canonicalToken.decimals,
      source: 'canonical',
    };
  }

  return {
    address: normalized,
    symbol: shortenAddress(normalized),
    name: normalized,
    source: 'fallback',
  };
}

export async function resolvePoolTokenDisplays(
  tokenRepo: TokenRepository,
  chainId: number,
  token0Address: string,
  token1Address: string
): Promise<{
  token0: ResolvedTokenDisplay;
  token1: ResolvedTokenDisplay;
}> {
  const [token0, token1] = await Promise.all([
    resolveTokenDisplay(tokenRepo, chainId, token0Address),
    resolveTokenDisplay(tokenRepo, chainId, token1Address),
  ]);

  return { token0, token1 };
}
