import { Injectable, Logger, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ethers } from 'ethers';

export interface BlockchainConfig {
  rpcUrl: string;
  chainId: number;
  gasPrice: string;
  gasLimit: string;
  contractAddress: string;
  privateKey: string;
  networkName: string;
}

@Injectable()
export class BlockchainService {
  private readonly logger = new Logger(BlockchainService.name);
  private provider: ethers.JsonRpcProvider | null = null;
  private signer: ethers.Wallet | null = null;

  constructor(@Inject(ConfigService) private configService: ConfigService) {}

  async initialize(): Promise<void> {
    try {
      const config = this.configService.get<BlockchainConfig>('blockchain');

      if (!config) {
        throw new Error('Blockchain configuration not found');
      }

      this.provider = new ethers.JsonRpcProvider(config.rpcUrl);
      this.signer = new ethers.Wallet(config.privateKey, this.provider);

      const network = await this.provider.getNetwork();
      this.logger.log(
        `Connected to blockchain network: ${network.name} (Chain ID: ${network.chainId})`,
      );
    } catch (error) {
      this.logger.error('Failed to initialize blockchain service', error);
      throw error;
    }
  }

  getProvider(): ethers.JsonRpcProvider {
    if (!this.provider) {
      throw new Error('Blockchain provider not initialized');
    }
    return this.provider;
  }

  getSigner(): ethers.Wallet {
    if (!this.signer) {
      throw new Error('Blockchain signer not initialized');
    }
    return this.signer;
  }

  async getBalance(address: string): Promise<string> {
    const balance = await this.provider!.getBalance(address);
    return ethers.formatEther(balance);
  }

  async getTransactionStatus(transactionHash: string): Promise<string | null> {
    const receipt = await this.provider!.getTransactionReceipt(transactionHash);
    return receipt?.status === 1 ? 'success' : 'failed';
  }
}
