import { Claim, ClaimKey, constructRead, extractRead, isResolvedRead } from '@coinweb/contract-kit';

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

export const readOp = <TClaim extends Claim = TypedClaim>(key: ClaimKey) => {
  return new Promise<TClaim | null>((resolve, reject) => {
    try {
      const { op, isOp } = shiftResolvedOp();

      if (!isOp) {
        pushAwaitedOp(constructRead(context.issuer, key));
      } else {
        if (op && !isResolvedRead(op)) {
          throw new Error('Read operation not found');
        }

        const claim = op && ((extractRead(op)?.[0]?.content ?? null) as TClaim | null);
        resolve(claim);
      }
    } catch (error) {
      reject(error);
    }
  });
};
