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

import { constructMutexExecOpsClaimStore } from '../claims';
import { MutexExecOpsResult, MutexSaveExecOpResultArgs } from '../types';

export const saveExecOpResult = (context: Context) => {
  const { availableCweb } = getCallParameters(context);

  const [execId, unavailableIndexes] = getMethodArguments<MutexSaveExecOpResultArgs>(context);
  const resolvedOps = extractContractArgs(context.tx);

  const result = new Array(resolvedOps.length + unavailableIndexes.length)
    .fill({ ok: false, error: 'Resource is busy' })
    .map((value: MutexExecOpsResult[number], i) => {
      if (unavailableIndexes.includes(i)) {
        return value;
      }

      const resolvedOp = resolvedOps.shift();

      if (!resolvedOp) {
        throw new Error('An error occurred while saving the exec op result');
      }

      return {
        ok: true as const,
        resolved: resolvedOp,
      };
    });

  return [constructContinueTx(context, [constructMutexExecOpsClaimStore(execId, result, availableCweb - 200n)])];
};
