<?php

declare(strict_types=1);

namespace KupShop\RecommendersBundle\Recommenders;

use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

class RecommendersLocator
{
    private $recommenders;

    public function __construct(iterable $recommenders)
    {
        $this->recommenders = $recommenders;
    }

    public function getTypes(): array
    {
        return array_keys($this->getRecommenders());
    }

    /**
     * @return IRecommender[]
     */
    public function getRecommenders(): array
    {
        $result = [];

        foreach ($this->recommenders as $recommender) {
            $result[$recommender::getType()] = $recommender;
        }

        return $result;
    }

    public function getRecommender(string $type): IRecommender
    {
        if ($recommender = $this->getRecommenders()[$type] ?? null) {
            return $recommender;
        }

        throw new ServiceNotFoundException($type, msg: "You have requested a non-existent recommender \"{$type}\".");
    }
}
