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

import { pushAwaitedOp } from '../awaited';
import { shiftResolvedOp } from '../resolved';

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

      if (!isOp) {
        pushAwaitedOp(constructStore(claim));
      } else {
        if (op && !isResolvedStore(op)) {
          throw new Error('Store operation not found');
        }

        const result = op && extractStore(op);

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