import { decodeEventLog, type Address, type TransactionReceipt } from "viem";
import { PONS_FACTORY, PONS_LOCKER, erc20Abi, ponsFactoryAbi, ponsLockerAbi } from "./contracts.js";

export const decodeLaunchReceipt = (receipt: TransactionReceipt) => {
  for (const log of receipt.logs) {
    if (log.address.toLowerCase() !== PONS_FACTORY.toLowerCase()) continue;
    try {
      const decoded = decodeEventLog({ abi: ponsFactoryAbi, data: log.data, topics: log.topics });
      if (decoded.eventName === "TokenLaunched") {
        return { token: decoded.args.token, pool: decoded.args.pool };
      }
    } catch {
      // Ignore unrelated factory logs.
    }
  }
  return null;
};

export const decodeClaimReceipt = (receipt: TransactionReceipt, token: Address) => {
  for (const log of receipt.logs) {
    if (log.address.toLowerCase() !== PONS_LOCKER.toLowerCase()) continue;
    try {
      const decoded = decodeEventLog({ abi: ponsLockerAbi, data: log.data, topics: log.topics });
      if (decoded.eventName === "FeesClaimed" && decoded.args.token.toLowerCase() === token.toLowerCase()) {
        return {
          token0: decoded.args.token0,
          token1: decoded.args.token1,
          recipientAmount0: decoded.args.recipientAmount0,
          recipientAmount1: decoded.args.recipientAmount1,
        };
      }
    } catch {
      // Ignore unrelated locker logs.
    }
  }
  return null;
};

export const decodeBuybackAcquired = (receipt: TransactionReceipt, token: Address, recipient: Address) => {
  let acquired = 0n;
  for (const log of receipt.logs) {
    if (log.address.toLowerCase() !== token.toLowerCase()) continue;
    try {
      const decoded = decodeEventLog({ abi: erc20Abi, data: log.data, topics: log.topics });
      if (decoded.eventName === "Transfer" && decoded.args.to.toLowerCase() === recipient.toLowerCase()) {
        acquired += decoded.args.value;
      }
    } catch {
      // Ignore unrelated token logs.
    }
  }
  return acquired;
};
