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

import { waitSteps } from '../settings';
import { MutexNotifyLockArgs, MutexWaitNotifyArgs } from '../types';

import { notifyLockMethodName, waitMethodName } from './names';

export const wait = (context: Context) => {
  const issuer = getContractIssuer(context);
  const [step, lockInfo] = getMethodArguments<MutexWaitNotifyArgs>(context);
  const { availableCweb } = getCallParameters(context);

  //Including the notifyLock method as step
  if (step + 1 < waitSteps) {
    return [
      constructContinueTx(
        context,
        [],
        [
          {
            callInfo: {
              ref: constructContractRef(issuer, []),
              methodInfo: {
                methodName: waitMethodName,
                methodArgs: [step + 1, lockInfo] satisfies MutexWaitNotifyArgs,
              },
              contractInfo: {
                providedCweb: availableCweb - 800n,
                authenticated: null,
              },
              contractArgs: [],
            },
          },
        ]
      ),
    ];
  }

  return [
    constructContinueTx(
      context,
      [],
      [
        {
          callInfo: {
            ref: constructContractRef(issuer, []),
            methodInfo: {
              methodName: notifyLockMethodName,
              methodArgs: [lockInfo] satisfies MutexNotifyLockArgs,
            },
            contractInfo: {
              providedCweb: availableCweb - 800n,
              authenticated: null,
            },
            contractArgs: [],
          },
        },
      ]
    ),
  ];
};
