import { JsonRpcProvider } from 'ethers';
import { BlockInfo, TransactionInfo, ChainStats } from '../types';

export class BlockModule {
  constructor(private provider: JsonRpcProvider) {}

  async getBlock(height: number): Promise<BlockInfo | null> {
    const block = await this.provider.getBlock(height);
    if (!block) return null;
    return {
      height: block.number,
      hash: block.hash!,
      timestamp: block.timestamp,
      txCount: block.transactions.length,
      proposer: block.miner,
    };
  }

  async getLatestBlock(): Promise<BlockInfo | null> {
    const block = await this.provider.getBlock('latest');
    if (!block) return null;
    return {
      height: block.number,
      hash: block.hash!,
      timestamp: block.timestamp,
      txCount: block.transactions.length,
      proposer: block.miner,
    };
  }

  async getTransaction(hash: string): Promise<TransactionInfo | null> {
    const [tx, receipt] = await Promise.all([
      this.provider.getTransaction(hash),
      this.provider.getTransactionReceipt(hash),
    ]);
    if (!tx) return null;

    const block = tx.blockNumber ? await this.provider.getBlock(tx.blockNumber) : null;

    return {
      hash: tx.hash,
      blockHeight: tx.blockNumber || 0,
      from: tx.from,
      to: tx.to || '',
      value: tx.value.toString(),
      gasUsed: receipt?.gasUsed.toString() || '0',
      status: receipt?.status === 1 ? 'success' : 'failed',
      timestamp: block?.timestamp || 0,
    };
  }

  async getStats(): Promise<ChainStats> {
    const block = await this.provider.getBlock('latest');
    return {
      blockHeight: block?.number || 0,
      tps: 0,
      activeAddresses: 0,
      totalCoupons: 0,
      totalVolume: '0',
    };
  }
}
