<?php

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Business\Model\EstablishmentWithTeam;
use NoahVet\Reef\Business\Model\Factory\EstablishmentWithTeamFactory;

/**
 * @psalm-import-type VeterinaryEstablishmentFilter from VeterinaryEstablishmentEnumeratorInterface
 */
class EstablishmentWithTeamEnumerator implements EstablishmentWithTeamEnumeratorInterface
{
    public function __construct(
        protected VeterinaryEstablishmentEnumeratorInterface $establishmentEnumerator,
        protected EstablishmentWithTeamFactory $establishmentWithTeamFactory,
    ) {
    }

    /**
     * @param VeterinaryEstablishmentFilter $establishmentFilters
     *
     * @return \Generator<EstablishmentWithTeam>
     */
    #[\Override]
    public function enumerateAll(
        int $establishmentBatchSize = 50,
        array $establishmentFilters = [],
    ): \Generator {
        $establishments = [];

        foreach ($this->establishmentEnumerator->enumerateAll($establishmentFilters, $establishmentBatchSize) as $establishment) {
            $establishments[] = $establishment;

            if (\count($establishments) === $establishmentBatchSize) {
                foreach ($this->establishmentWithTeamFactory->createBatch($establishments) as $item) {
                    yield $item;
                }
                $establishments = [];
            }
        }

        if (!empty($establishments)) {
            foreach ($this->establishmentWithTeamFactory->createBatch($establishments) as $item) {
                yield $item;
            }
        }
    }
}
