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

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

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

  async getTransaction(hash: string) {
    const [tx, receipt] = await Promise.all([
      this.provider.getTransaction(hash),
      this.provider.getTransactionReceipt(hash),
    ]);
    if (!tx) return null;
    return {
      hash: tx.hash,
      blockNumber: tx.blockNumber,
      from: tx.from,
      to: tx.to,
      value: tx.value.toString(),
      gasPrice: tx.gasPrice?.toString(),
      gasUsed: receipt?.gasUsed.toString(),
      status: receipt?.status === 1 ? 'success' : 'failed',
      timestamp: tx.blockNumber
        ? (await this.provider.getBlock(tx.blockNumber))?.timestamp
        : null,
    };
  }
}
