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

import { opMarker } from '../../global';
import { isResolvedSlotOp, isResolvedStoreOp } from '../../utils';
import { pushAwaitedTask } from '../awaited';
import { shiftResolvedOp } from '../resolved';

export const storeOp = (claim: Claim) => {
  console.log('storeOp');
  let opMarkerValue = false;

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

      if (!isOp) {
        pushAwaitedTask(constructStore(claim));
        opMarkerValue = true;
      } else {
        if (isResolvedSlotOp(op)) {
          console.log('storeOp-slotOp');
          return;
        }

        if (!isResolvedStoreOp(op)) {
          console.log('storeOp-error');
          throw new Error('Store operation not found');
        }

        const result = op && extractStore(op);

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

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

  return result;
};
