<?php

namespace NoahVet\Reef\Domain\Http;

use NoahVet\Reef\Jane\Exception\BadRequestException;

/**
 * @template T
 *
 * @deprecated
 */
class ReefEnumerator
{
    /**
     * @param callable(array<mixed>): list<T> $apicall
     * @param array<mixed>|null               $filters
     */
    public function __construct(
        private readonly mixed $apicall,
        private readonly ?array $filters = null,
        private readonly int $querySize = 50,
    ) {
    }

    /**
     * @return \Generator<T>
     */
    public function __invoke(): \Generator
    {
        for ($page = 0; true; ++$page) {
            try {
                $items = \call_user_func(
                    $this->apicall,
                    \array_merge($this->filters ?? [], ['page' => $page, 'limit' => $this->querySize]),
                );

                foreach ($items as $item) {
                    yield $item;
                }

                if (\count($items) < $this->querySize) {
                    break;
                }
            } catch (BadRequestException) {
                // End of enumeration
                break;
            }
        }
    }
}
