<?php

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\GetAllVeterinaryEstablishmentBadRequestException;
use NoahVet\Reef\Jane\Model\VeterinaryEstablishmentResponse;

/**
 * @psalm-import-type VeterinaryEstablishmentFilter from VeterinaryEstablishmentEnumeratorInterface
 */
class VeterinaryEstablishmentEnumerator implements VeterinaryEstablishmentEnumeratorInterface
{
    public function __construct(
        protected Client $internalServiceClient,
    ) {
    }

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

                \assert(\is_array($establishments));

                foreach ($establishments as $establishment) {
                    yield $establishment;
                }

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