import { Claim, ClaimKey, constructRangeRead, extractRead } from '@coinweb/contract-kit';
import { ClaimRange } from '@coinweb/contract-kit/dist/types/operations/read';

import { TypedClaim } from '../../../types';
import { context } from '../../context';
import { opMarker } from '../../globals/promise';
import { isResolvedReadOp, isResolvedSlotOp } from '../../utils';
import { pushAwaitedTask, shiftResolvedOp } from '../../runtime';

export const rangeReadOp = <TClaims extends Claim[] = TypedClaim[]>(
  firstPart: ClaimKey['first_part'],
  range: ClaimRange,
  maxCount: number
) => {
  let opMarkerValue = false;

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

      if (!isOp) {
        pushAwaitedTask(constructRangeRead(context.issuer, firstPart, range, maxCount));
        opMarkerValue = true;
      } else {
        if (isResolvedSlotOp(op)) {
          return;
        }

        if (!isResolvedReadOp(op)) {
          throw new Error('Read operation not found');
        }

        const claim = (extractRead(op)?.map((result) => result.content) ?? null) as TClaims | null;
        resolve(claim);
      }
    } catch (error) {
      reject(error);
    }
  });

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

  return result;
};
