import { JsonRpcProvider, Contract, Signer } from 'ethers';
import { SwapParams } from '../types';
import { SETTLEMENT_ABI, SETTLEMENT_ADDRESS } from '../contracts/abis';

export class SettlementModule {
  private settlement: Contract;

  constructor(private provider: JsonRpcProvider) {
    this.settlement = new Contract(SETTLEMENT_ADDRESS, SETTLEMENT_ABI, provider);
  }

  /**
   * 执行券原子交换（需要签名器）
   * @param params 交换参数（tokenId, buyer, seller, price, stablecoin）
   * @param signer 签名器（MPC签名器或钱包）
   */
  async executeSwap(params: SwapParams, signer: Signer): Promise<string> {
    const contract = this.settlement.connect(signer) as Contract;
    const tx = await contract.executeSwap(
      params.tokenId,
      params.buyer,
      params.seller,
      params.price,
      params.stablecoin,
    );
    const receipt = await tx.wait();
    return receipt.hash;
  }

  /**
   * 监听 SwapExecuted 事件
   */
  onSwapExecuted(callback: (tokenId: string, buyer: string, seller: string, price: string) => void): void {
    this.settlement.on('SwapExecuted', (tokenId, buyer, seller, price) => {
      callback(tokenId.toString(), buyer, seller, price.toString());
    });
  }
}
