<?php

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\GetAllLegalStructureBadRequestException;
use NoahVet\Reef\Jane\Model\LegalStructureResponseItem;

/**
 * @psalm-import-type LegalStructureFilter from LegalStructureEnumeratorInterface
 */
class LegalStructureEnumerator implements LegalStructureEnumeratorInterface
{
    public function __construct(
        protected Client $internalServiceClient,
    ) {
    }

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

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

                foreach ($structures as $structure) {
                    yield $structure;
                }

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