/**
 * DeBank Cloud API — portfolio/balance aggregation (optional).
 * https://docs.cloud.debank.com
 * Requires DEBANK_API_KEY env var.
 */

const DEBANK_API_BASE = 'https://pro-openapi.debank.com';

export interface DeBankTotalBalance {
  total_usd_value: number;
  chain_list: Array<{
    id: string;
    name: string;
    usd_value: number;
    logo_url?: string;
  }>;
}

export interface DeBankChainBalance {
  usd_value: number;
}

/**
 * Get total balance across all supported chains.
 */
export async function getDeBankTotalBalance(address: string): Promise<DeBankTotalBalance | null> {
  const apiKey = process.env.DEBANK_API_KEY;
  if (!apiKey) return null;
  try {
    const url = `${DEBANK_API_BASE}/v1/user/total_balance?id=${encodeURIComponent(address)}`;
    const res = await fetch(url, {
      headers: { Accept: 'application/json', AccessKey: apiKey },
      signal: AbortSignal.timeout(5000),
    });
    if (!res.ok) return null;
    return (await res.json()) as DeBankTotalBalance;
  } catch {
    return null;
  }
}

/**
 * Get balance for a specific chain (DeBank uses chain slugs: eth, bsc, matic, etc).
 */
export async function getDeBankChainBalance(address: string, chainId: string): Promise<DeBankChainBalance | null> {
  const apiKey = process.env.DEBANK_API_KEY;
  if (!apiKey) return null;
  try {
    const url = `${DEBANK_API_BASE}/v1/user/chain_balance?id=${encodeURIComponent(address)}&chain_id=${encodeURIComponent(chainId)}`;
    const res = await fetch(url, {
      headers: { Accept: 'application/json', AccessKey: apiKey },
      signal: AbortSignal.timeout(5000),
    });
    if (!res.ok) return null;
    return (await res.json()) as DeBankChainBalance;
  } catch {
    return null;
  }
}
