<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\ApplicationSystem;

use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Entity\EditionTask;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Exception\AmbiguousApplicationSystemException;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
use Symfony\Component\DependencyInjection\ServiceLocator;

class ApplicationSystems
{
    public function __construct(#[AutowireLocator('ferienpass.application_system', defaultIndexMethod: 'getType')] private readonly ServiceLocator $applicationSystems)
    {
    }

    public function findApplicationSystem(OfferInterface|Edition $entity): ?ApplicationSystemInterface
    {
        if ($entity instanceof OfferInterface) {
            $entity = $entity->getEdition();
        }

        // When the Ferienpass is configured without editions, use the "first come-first served" application procedure
        if (!$entity instanceof Edition) {
            if ($this->applicationSystems->has('firstcome')) {
                return $this->applicationSystems->get('firstcome');
            }

            throw new \RuntimeException('Application system "firstcome" is unknown');
        }

        $tasks = $entity->getTasks()->filter(
            static fn (EditionTask $t) => 'application_system' === $t->getType()
                && $t->getApplicationSystem()
                && $t->isActive()
        );

        if ($tasks->count() > 1) {
            throw new AmbiguousApplicationSystemException('More than one application system is applicable at the moment for pass edition ID '.$entity->getId());
        }

        /** @var EditionTask $task */
        if ($tasks->isEmpty() || false === $task = $tasks->current()) {
            return null;
        }

        $applicationSystem = $this->applicationSystems->get($task->getApplicationSystem());
        if (!$applicationSystem instanceof ApplicationSystemInterface) {
            throw new \RuntimeException(\sprintf('Application system "%s" is unknown', $task->getApplicationSystem()));
        }

        return $applicationSystem->withTask($task);
    }
}
