import { Contract, JsonRpcProvider, TransactionResponse, Wallet, ethers } from 'ethers';

export interface BlockchainConfig {
  providerUrl: string;
  privateKey: string;
  liquidityManagerAddress: string;
  stakeContractAddress: string;
}

const LM_ABI = [
  { type: 'function', name: 'recenter', inputs: [], outputs: [], stateMutability: 'nonpayable' },
  { type: 'function', name: 'feeDestination', inputs: [], outputs: [{ type: 'address' }], stateMutability: 'view' },
];

const STAKE_ABI = [
  {
    inputs: [{ internalType: 'uint256', name: 'positionId', type: 'uint256' }],
    name: 'payTax',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
  },
];

export class BlockchainService {
  private readonly provider: JsonRpcProvider;
  private readonly wallet: Wallet;
  private readonly liquidityManager: Contract;
  private readonly stakeContract: Contract;

  constructor(config: BlockchainConfig) {
    this.provider = new ethers.JsonRpcProvider(config.providerUrl);
    this.wallet = new ethers.Wallet(config.privateKey, this.provider);
    this.liquidityManager = new ethers.Contract(config.liquidityManagerAddress, LM_ABI, this.wallet);
    this.stakeContract = new ethers.Contract(config.stakeContractAddress, STAKE_ABI, this.wallet);
  }

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

  async estimateRecenterGas(): Promise<void> {
    await this.liquidityManager.recenter.estimateGas();
  }

  async recenter(): Promise<TransactionResponse> {
    return (await this.liquidityManager.recenter()) as TransactionResponse;
  }

  async payTax(positionId: bigint): Promise<TransactionResponse> {
    return (await this.stakeContract.payTax(positionId)) as TransactionResponse;
  }
}
