import { Claim, constructStore } from '@coinweb/contract-kit';
import { extractStore } from '@coinweb/contract-kit/dist/esm/operations/store';

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

export const storeOp = (claim: Claim, storeCweb?: bigint) => {
  let opMarkerValue = false;

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

      if (!isOp) {
        pushAwaitedTask({ ...constructStore(claim), providedCweb: storeCweb });
        opMarkerValue = true;
      } else {
        if (isResolvedSlotOp(op)) {
          return;
        }

        if (!isResolvedStoreOp(op)) {
          throw new Error('Store operation not found');
        }

        const result = extractStore(op);

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

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

  return result;
};
