import { Claim, ClaimKey, constructTake, extractTake } from '@coinweb/contract-kit';

import { TypedClaim } from '../../../types';
import { opMarker } from '../../globals/promise';
import { isResolvedSlotOp, isResolvedTakeOp } from '../../utils';
import { pushAwaitedTask, shiftResolvedOp } from '../../runtime';

export const takeOp = <TClaim extends Claim = TypedClaim>(key: ClaimKey) => {
  let opMarkerValue = false;

  const result = new Promise<TClaim | null>((resolve, reject) => {
    try {
      const { op, isOp } = shiftResolvedOp();

      if (!isOp) {
        pushAwaitedTask(constructTake(key));
        opMarkerValue = true;
      } else {
        if (isResolvedSlotOp(op)) {
          return;
        }

        if (!isResolvedTakeOp(op)) {
          throw new Error('Take operation not found');
        }

        const claim = extractTake(op);
        resolve(claim as TClaim | null);
      }
    } catch (error) {
      reject(error);
    }
  });

  (result as Promise<TClaim | null> & { [opMarker]: boolean })[opMarker] = opMarkerValue;

  return result;
};
