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

import { MutexPreReadTakeOpsArgs, MutexSaveExecOpResultArgs } from '../types';

import { saveExecOpResultMethodName } from './names';

export const preReadExecTakeOps = (context: Context) => {
  const { availableCweb } = getCallParameters(context);
  const issuer = getContractIssuer(context);

  const [execId, unavailableIndexes, ops] = getMethodArguments<MutexPreReadTakeOpsArgs>(context);

  const storedCweb = extractContractArgs(context.tx)
    .map((op) => BigInt(extractRead(op)?.[0]?.content.fees_stored ?? 0))
    .reduce((total, op) => total + op, 0n);

  const fee = 700n + BigInt(ops.length) * 100n;

  return [
    constructContinueTx(
      context,
      [passCwebFrom(issuer, availableCweb)],
      [
        {
          callInfo: {
            ref: constructContractRef(issuer, []),
            methodInfo: {
              methodName: saveExecOpResultMethodName,
              methodArgs: [execId, unavailableIndexes] satisfies MutexSaveExecOpResultArgs,
            },
            contractInfo: {
              providedCweb: availableCweb + storedCweb - fee,
              authenticated: null,
            },
            contractArgs: ops,
          },
        },
      ]
    ),
  ];
};
