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

@Injectable()
export class ExportService {
  private provider: JsonRpcProvider;

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

  async exportTransactions(fromBlock: number, toBlock: number) {
    if (toBlock - fromBlock > 10000) {
      throw new BadRequestException('Maximum 10,000 blocks per export');
    }

    const transactions: any[] = [];
    for (let i = fromBlock; i <= toBlock; i++) {
      const block = await this.provider.getBlock(i, true);
      if (!block) continue;
      for (const txHash of block.transactions) {
        const tx = await this.provider.getTransaction(txHash as string);
        if (tx) {
          transactions.push({
            hash: tx.hash,
            blockNumber: tx.blockNumber,
            from: tx.from,
            to: tx.to,
            value: tx.value.toString(),
            gasPrice: tx.gasPrice?.toString(),
            timestamp: block.timestamp,
          });
        }
      }
    }

    return { fromBlock, toBlock, count: transactions.length, transactions };
  }

  toCsv(data: any): string {
    if (!data.transactions.length) return 'hash,blockNumber,from,to,value,gasPrice,timestamp\n';
    const headers = Object.keys(data.transactions[0]).join(',');
    const rows = data.transactions.map((tx: any) => Object.values(tx).join(','));
    return [headers, ...rows].join('\n');
  }
}
