<?php

declare(strict_types=1);

namespace NoahVet\Reef\Business\Enumerator;

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

class VeterinaryGroupEnumerator
{
    public function __construct(
        protected Client $client,
    ) {
    }

    /**
     * @param array{
     *     isRegularized?: bool,
     *     vguUser?: string[],
     *     id?: string[],
     *     veterinaryEstablishmentId?: string[],
     *     vguUserId?: string[],
     *     entitled?: string[],
     *     groupCode?: string[],
     *     fromCreatedDate?: string[],
     *     fromUpdatedDate?: string[],
     *     toCreatedDate?: string[],
     *     toUpdatedDate?: string[],
     *     sortCreatedDate?: string,
     *     sortEntryNumber?: string,
     *     sortGroupCode?: string,
     *     sortName?: string,
     *     sortType?: string,
     *     sortUpdatedDate?: string
     * } $filters
     *
     * @return \Generator<VeterinaryGroupResponse>
     *
     * @see Client::getAllVeterinaryGroup
     */
    public function enumerateAll(array $filters = [], int $querySize = 50): \Generator
    {
        for ($page = 0; true; ++$page) {
            try {
                $groups = $this->client->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;
            }
        }
    }
}
