import {
  addAssets,
  Data,
  LucidEvolution,
  OutRef,
  TxBuilder,
  UTxO,
} from '@lucid-evolution/lucid';
import {
  fromSystemParamsScriptRef,
  SystemParams,
} from '../../types/system-params';
import { matchSingle } from '../../utils/utils';
import { serialiseCollectorRedeemer } from './types-new';
import { mkLovelacesOf } from '@3rd-eye-labs/cardano-offchain-common';

/**
 * Returns the collector ref script UTXO that was added to ref inputs.
 *
 * No need to return the TxBuilder since it's stateful object.
 */
export async function collectorFeeTx(
  fee: bigint,
  lucid: LucidEvolution,
  params: SystemParams,
  tx: TxBuilder,
  collectorOref: OutRef,
): Promise<UTxO> {
  const collectorUtxo: UTxO = matchSingle(
    await lucid.utxosByOutRef([collectorOref]),
    (_) => new Error('Expected a single collector UTXO'),
  );

  const collectorRefScriptUtxo = matchSingle(
    await lucid.utxosByOutRef([
      fromSystemParamsScriptRef(params.scriptReferences.collectorValidatorRef),
    ]),
    (_) => new Error('Expected a single collector Ref Script UTXO'),
  );

  tx.collectFrom([collectorUtxo], serialiseCollectorRedeemer('Collect'))
    .pay.ToContract(
      collectorUtxo.address,
      { kind: 'inline', value: Data.void() },
      addAssets(collectorUtxo.assets, mkLovelacesOf(fee)),
    )
    .readFrom([collectorRefScriptUtxo]);

  return collectorRefScriptUtxo;
}
