<?php

declare(strict_types=1);

namespace App\Service\ServiceIterator\Mailer;

use App\Service\Mailer\Model\MailerModelInterface;
use App\Service\Mailer\Builder\BuilderInterface;
use Exception;
use RuntimeException;

/**
 * Permet d'itérer sur les services de build Mailer
 */
class BuilderIterator
{
    /**
     * Pour l'injection des services, voir config/services.yaml, section 'TAG Services'
     * @param iterable<BuilderInterface> $builderServices
     */
    public function __construct(
        readonly private iterable $builderServices,
    ) {}

    /**
     * Itère sur les services de build disponibles et
     * retourne le premier qui supporte ce type de requête.
     *
     * @param MailerModelInterface $mailerModel
     * @return BuilderInterface
     * @throws Exception
     */
    public function getBuilderFor(MailerModelInterface $mailerModel): BuilderInterface
    {
        /** @var BuilderInterface $builderService */
        foreach ($this->builderServices as $builderService){
            if($builderService->support($mailerModel)) {
                return $builderService;
            }
        }
        throw new RuntimeException('no builder service found for this operation');
    }
}
