import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JsonRpcProvider } from 'ethers';

export interface ChainEvent {
  type: 'newBlock' | 'largeTx' | 'compliance' | 'couponMint';
  blockHeight: number;
  timestamp: number;
  data: Record<string, any>;
}

@Injectable()
export class EventsService implements OnModuleDestroy {
  private provider: JsonRpcProvider;
  private listening = false;

  constructor(private config: ConfigService) {
    this.provider = new JsonRpcProvider(this.config.get('rpcUrl'));
  }

  startListening(broadcast: (event: ChainEvent) => void) {
    if (this.listening) return;
    this.listening = true;

    this.provider.on('block', async (blockNumber: number) => {
      const block = await this.provider.getBlock(blockNumber);
      if (!block) return;

      broadcast({
        type: 'newBlock',
        blockHeight: block.number,
        timestamp: block.timestamp,
        data: {
          hash: block.hash,
          txCount: block.transactions.length,
          gasUsed: block.gasUsed.toString(),
        },
      });
    });
  }

  onModuleDestroy() {
    this.provider.removeAllListeners();
  }
}
