import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JsonRpcProvider, Contract } from 'ethers';
import { COUPON_FACTORY_ABI } from '../../contracts/abis/coupon.abi';
import { CONTRACT_ADDRESSES } from '../../contracts/addresses';

@Injectable()
export class StatsService {
  private provider: JsonRpcProvider;
  private factoryContract: Contract;

  constructor(private config: ConfigService) {
    this.provider = new JsonRpcProvider(this.config.get('rpcUrl'));
    this.factoryContract = new Contract(CONTRACT_ADDRESSES.couponFactory, COUPON_FACTORY_ABI, this.provider);
  }

  async getStats() {
    const [latestBlock, totalBatches] = await Promise.all([
      this.provider.getBlock('latest'),
      this.factoryContract.totalBatches().catch(() => 0n),
    ]);

    // 计算近100个区块的TPS
    let tps = 0;
    if (latestBlock && latestBlock.number > 100) {
      const oldBlock = await this.provider.getBlock(latestBlock.number - 100);
      if (oldBlock) {
        const timeDiff = latestBlock.timestamp - oldBlock.timestamp;
        tps = timeDiff > 0 ? Math.round((100 * latestBlock.transactions.length) / timeDiff) : 0;
      }
    }

    return {
      blockHeight: latestBlock?.number || 0,
      blockHash: latestBlock?.hash,
      timestamp: latestBlock?.timestamp,
      tps,
      chainId: this.config.get('chainId'),
      totalCouponBatches: Number(totalBatches),
    };
  }
}
