const MEMPOOL_API = 'https://mempool.space/api/blocks/tip';

export interface LastBlock {
  id: string;
  height: number;
  version: number;
  timestamp: number;
  tx_count: number;
  size: number;
  weight: number;
  merkle_root: string;
  previousblockhash: string;
  mediantime: number;
  nonce: number;
  bits: number;
  difficulty: number;
  error?: string;
}

export async function getLastBlock(): Promise<LastBlock> {
  try {
    const response = await fetch(MEMPOOL_API);

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    const latestBlock = data[0];
    if (!latestBlock) throw new Error('Failed to fetch block');
    return latestBlock;
  } catch (e) {
    return {
      id: '',
      height: 0,
      version: 0,
      timestamp: 0,
      tx_count: 0,
      size: 0,
      weight: 0,
      merkle_root: '',
      previousblockhash: '',
      mediantime: 0,
      nonce: 0,
      bits: 0,
      difficulty: 0,
      error: e instanceof Error ? e.message : 'Failed to fetch block',
    };
  }
}
