<?php
declare(strict_types=1);

namespace App\Service\ServiceIterator;

use App\Entity\Core\File;
use App\Service\File\Storage\FileStorageInterface;
use Exception;
use RuntimeException;

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

    /**
     * Itère sur les services de storage disponibles et
     * retourne le premier qui supporte ce type de requête.
     *
     * @param File $file
     * @return FileStorageInterface
     * @throws Exception
     */
    public function getStorageFor(File $file): FileStorageInterface
    {
        /** @var FileStorageInterface $storageService */
        foreach ($this->storageServices as $storageService){
            if($storageService->support($file)) {
                return $storageService;
            }
        }
        throw new RuntimeException('no storage service found for this File');
    }
}
