<?php

declare(strict_types=1);

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\GetAllManufacturerBadRequestException;
use NoahVet\Reef\Jane\Model\ManufacturerResponseItem;

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

    /**
     * @param ?string[] $idFilter
     *
     * @return \Generator<string, ManufacturerResponseItem>
     */
    public function enumerateAll(?array $idFilter = null, int $querySize = 50): \Generator
    {
        for ($page = 0; true; ++$page) {
            try {
                $params = ['page' => $page, 'limit' => $querySize];
                if (null !== $idFilter && !empty($idFilter)) {
                    $params['id'] = $idFilter;
                }

                $manufacturers = $this->client->getAllManufacturer($params);

                \assert(\is_array($manufacturers));

                foreach ($manufacturers as $manufacturer) {
                    yield $manufacturer->getId() => $manufacturer;
                }

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