<?php

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\GetAllVeterinaryGroupBadRequestException;
use NoahVet\Reef\Jane\Model\VeterinaryGroupResponse;

/**
 * @psalm-import-type VeterinaryGroupFilter from VeterinaryGroupEnumeratorInterface
 */
class VeterinaryGroupEnumerator implements VeterinaryGroupEnumeratorInterface
{
    public function __construct(
        protected Client $internalServiceClient,
    ) {
    }

    /**
     * @param VeterinaryGroupFilter $filters
     *
     * @return \Generator<VeterinaryGroupResponse>
     *
     * @see Client::getAllVeterinaryGroup
     */
    #[\Override]
    public function enumerateAll(array $filters = [], int $querySize = 50): \Generator
    {
        for ($page = 0; true; ++$page) {
            try {
                $groups = $this->internalServiceClient->getAllVeterinaryGroup(
                    \array_merge($filters, ['page' => $page, 'limit' => $querySize]),
                );

                if (!\is_array($groups)) {
                    throw new \LogicException("Can't parse BSM response");
                }

                foreach ($groups as $group) {
                    yield $group;
                }

                if (\count($groups) < $querySize) {
                    break;
                }
            } catch (GetAllVeterinaryGroupBadRequestException) {
                // End of enumeration
                break;
            }
        }
    }
}
