import { constructContinueTx, constructDataUnverified } from '@coinweb/contract-kit';
import { getCallParameters } from 'lib/onchain';

import { getRawContext } from '../../context';
import { getAwaitedTasks } from '../../promisifiedOps';

import { prepareInThreadTxs } from './prepareInThreadTxs';
import { prepareOutThreadTxs } from './prepareOutThreadTxs';
import { splitTasks } from './splitTasks';

export const prepareTx = (isFullyExecuted: boolean, callsCount?: number) => {
  console.log('Calls Count: ', callsCount);

  const ctx = getRawContext();
  const awaitedTasks = getAwaitedTasks();

  console.log('Awaited Tasks: ', JSON.stringify(awaitedTasks));

  if (!awaitedTasks.length) {
    return { tx: [constructContinueTx(ctx, [constructDataUnverified({ isFullyExecuted })])], calls: 0 };
  }

  const { inThreadTasks, outThreadTasks } = splitTasks(awaitedTasks, isFullyExecuted);

  const { availableCweb } = getCallParameters(ctx);
  const cwebPerCall = availableCweb / BigInt(callsCount || 1);
  const {
    txs: outThreadTxs,
    fee: outThreadFee,
    calls: outThreadCallsPrepared,
  } = prepareOutThreadTxs({ tasks: outThreadTasks, cwebPerCall });

  const { txs: inThreadTxs, calls: inThreadCallsPrepared } = prepareInThreadTxs({
    tasks: inThreadTasks,
    cwebPerCall,
    outThread: outThreadTasks.length,
    outThreadFee,
  });

  return { tx: [...inThreadTxs, ...outThreadTxs], calls: inThreadCallsPrepared + outThreadCallsPrepared };
};
