<?php

declare(strict_types=1);

class WebserviceSpecificManagementRecommandationsProducts implements WebserviceSpecificManagementInterface
{
    /** @var WebserviceOutputBuilderCore|null */
    protected $objOutput;

    /**
     * @var mixed
     */
    protected $output;

    /** @var WebserviceRequestCore|null */
    protected $wsObject;

    private \Symfony\Component\DependencyInjection\ContainerInterface $container;

    private \Myvetshop\Module\Clinique\Presenter\ProductPresenter $productPresenter;

    public function __construct()
    {
        $container = PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance();

        \assert(null !== $container);

        $this->container = $container;
        $productPresenter = $this->container->get(
            \Myvetshop\Module\Clinique\Presenter\ProductPresenter::class
        );

        \assert($productPresenter instanceof \Myvetshop\Module\Clinique\Presenter\ProductPresenter);

        $this->productPresenter = $productPresenter;
    }

    public function setObjectOutput(WebserviceOutputBuilderCore $obj): self
    {
        $this->objOutput = $obj;

        return $this;
    }

    public function getObjectOutput(): ?WebserviceOutputBuilderCore
    {
        return $this->objOutput;
    }

    public function setWsObject(WebserviceRequestCore $obj): self
    {
        $this->wsObject = $obj;

        return $this;
    }

    public function getWsObject(): ?WebserviceRequestCore
    {
        return $this->wsObject;
    }

    public function manage(): void
    {
        $ret = [];

        try {
            switch ($_SERVER['REQUEST_METHOD']) {
                case 'GET':
                    if (
                        isset($this->wsObject->urlSegment[0])
                        && 'recommandationsProducts' === $this->wsObject->urlSegment[0]
                        && isset($this->wsObject->urlSegment[1])
                    ) {
                        $ret = $this->productPresenter->present(new \Product((int) $this->wsObject->urlSegment[1]));
                    }
                    break;
            }

            echo \json_encode($ret, \JSON_PRETTY_PRINT);
            exit;
        } catch (\Exception $exception) {
            \header('Content-Type: application/json');
            \http_response_code(500);
            echo \json_encode(['error' => $exception->getMessage()]);
            exit;
        }
    }

    /**
     * This must be return an array with specific values as WebserviceRequest expects.
     *
     * @return array<mixed>|string
     */
    public function getContent()
    {
        if (!$this->objOutput) {
            return [];
        }

        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
