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

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

import { notifyLockMethodName } from './names';

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

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

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