import { ethers } from 'ethers';
import type { PaymentLeaf } from './ingress/types';
import { effectiveValue } from './leafCodec';

const MIRROR_ABI = [
  'function mirrorBatchTransactions(bytes32[] calldata txHashes, address[] calldata froms, address[] calldata tos, uint256[] calldata values, uint256[] calldata blockNumbers, uint256[] calldata blockTimestamps, uint256[] calldata gasUseds, bool[] calldata successes, bytes[] calldata datas) external',
  'function processed(bytes32) view returns (bool)',
];

export async function dualWriteV1Mirror(
  wallet: ethers.Wallet,
  mirrorAddress: string,
  leaves: PaymentLeaf[]
): Promise<string | null> {
  if (leaves.length === 0) return null;
  const mirror = new ethers.Contract(mirrorAddress, MIRROR_ABI, wallet);

  const pending: PaymentLeaf[] = [];
  for (const leaf of leaves) {
    try {
      if (await mirror.processed(leaf.txHash)) continue;
    } catch {
      /* continue */
    }
    pending.push(leaf);
  }
  if (pending.length === 0) return null;

  const tx = await mirror.mirrorBatchTransactions(
    pending.map((l) => l.txHash),
    pending.map((l) => l.from),
    pending.map((l) => l.to),
    pending.map((l) => effectiveValue(l)),
    pending.map((l) => l.blockNumber),
    pending.map((l) => l.blockTimestamp),
    pending.map((l) => l.gasUsed),
    pending.map((l) => l.success),
    pending.map((l) => '0x')
  );
  await tx.wait();
  return tx.hash as string;
}
