<?php
declare(strict_types=1);

namespace App\Service\ServiceIterator;

use App\ApiResources\Export\ExportRequest;
use App\Service\Export\ExporterInterface;
use Exception;
use RuntimeException;

/**
 * Permet d'itérer sur les services d'export
 */
class ExporterIterator
{
    /**
     * Pour l'injection des services, voir config/services.yaml, section 'TAG Services'
     * @param iterable<ExporterInterface> $exportServices
     */
    public function __construct(
        readonly private iterable $exportServices,
    ) {}

    /**
     * Itère sur les services d'export disponibles et
     * retourne le premier qui supporte ce type de requête.
     *
     * @param ExportRequest $exportRequest
     * @return ExporterInterface
     * @throws Exception
     */
    public function getExporterFor(ExportRequest $exportRequest): ExporterInterface
    {
        /** @var ExporterInterface $exportService */
        foreach ($this->exportServices as $exportService){
            if($exportService->support($exportRequest)) {
                return $exportService;
            }
        }
        throw new RuntimeException('no export service found for this export request');
    }
}
