import { BlockFilter, constructBlock, extractBlock } from '@coinweb/contract-kit';

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

export const blockOp = (filters: BlockFilter[]) => {
  let opMarkerValue = false;

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

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

        if (!isResolvedBlockOp(op)) {
          throw new Error('Block operation not found');
        }

        const result = extractBlock(op);

        resolve(result);
      }
    } catch (error) {
      reject(error);
    }
  });

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

  return result;
};
