<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout;

use Gls\GlsPoland\EventDispatcher\Adapter\EventDispatcher;
use Gls\GlsPoland\PrestaShop\Checkout\Event\AbstractCheckoutEvent;
use Gls\GlsPoland\PrestaShop\ModuleRepository;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Service\ServiceProviderInterface;

final class CheckoutResolver implements CheckoutResolverInterface
{
    private $container;
    private $controller;
    private $moduleRepository;
    private $dispatcher;

    /**
     * @var CheckoutInterface|null
     */
    private $checkout;
    private $resolved = false;

    /**
     * @param ServiceProviderInterface<CheckoutInterface> $container
     */
    public function __construct(ContainerInterface $container, \FrontController $controller, ModuleRepository $moduleRepository)
    {
        if ($container instanceof ServiceProviderInterface) {
            $this->container = $container;
        } else {
            @trigger_error(sprintf('Passing a container that does not implement "%s" to "%s::__construct()" is deprecated since version 1.1.0.', ServiceProviderInterface::class, __CLASS__), E_USER_DEPRECATED);
            $this->container = self::decorateContainer($container);
        }
        $this->controller = $controller;
        $this->moduleRepository = $moduleRepository;
        $this->dispatcher = new EventDispatcher();
    }

    public function resolve(?Request $request = null): ?CheckoutInterface
    {
        if (null !== $this->checkout) {
            return $this->checkout;
        }

        if ($this->resolved) {
            return null;
        }

        $this->checkout = $this->doResolve($request);
        $this->resolved = true;

        if (null === $this->checkout) {
            return null;
        }

        $this->checkout->setController($this->controller);
        $this->dispatcher->addSubscriber($this->checkout);

        return $this->checkout;
    }

    public function dispatch(AbstractCheckoutEvent $event): AbstractCheckoutEvent
    {
        $this->resolve($event->getRequest());

        return $this->dispatcher->dispatch($event);
    }

    private function doResolve(?Request $request): ?CheckoutInterface
    {
        foreach ($this->container->getProvidedServices() as $id => $type) {
            if ('' === $type) {
                $type = (string) $id;
            } elseif ('?' === $type[0]) {
                $type = substr($type, 1);
            }

            if (!is_subclass_of($type, ModuleCheckoutInterface::class)) {
                continue;
            }

            if (!is_callable([$type, 'supports'])) {
                continue;
            }

            if (!$type::supports($this->controller, $this->moduleRepository, $request)) {
                continue;
            }

            return $this->container->get($id);
        }

        if (!$this->controller instanceof \OrderControllerCore) {
            return null;
        }

        return $this->container->get(NativeCheckout::class);
    }

    private static function decorateContainer(ContainerInterface $container): ServiceProviderInterface
    {
        return new class($container) implements ServiceProviderInterface {
            private $container;

            public function __construct(ContainerInterface $container)
            {
                $this->container = $container;
            }

            public function get(string $id)
            {
                return $this->container->get($id);
            }

            public function has(string $id): bool
            {
                return $this->container->has($id);
            }

            public function getProvidedServices(): array
            {
                if (!$this->container->has(NativeCheckout::class)) {
                    return [];
                }

                return [NativeCheckout::class => CheckoutInterface::class];
            }
        };
    }
}
