<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Context;

use MonsieurBiz\SyliusSearchPlugin\Exception\TaxonNotFoundException;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class RequestTaxonContext implements TaxonContextInterface
{
    public function __construct(
        private readonly RequestStack $requestStack,
        private readonly TaxonRepositoryInterface $taxonRepository,
        private readonly LocaleContextInterface $localeContext,
    ) {
    }

    public function getTaxon(): TaxonInterface
    {
        $request = $this->requestStack->getCurrentRequest();

        if (null === $request) {
            throw new \Exception('No request found');
        }

        $slug = $request->get('slug');
        if (null === $slug) {
            throw new TaxonNotFoundException();
        }
        $slug = htmlspecialchars($slug);
        $localeCode = $this->localeContext->getLocaleCode();

        /** @var TaxonInterface|null $taxon */
        $taxon = $this->taxonRepository->findOneBySlug($slug, $localeCode);

        if (null === $taxon) {
            throw new TaxonNotFoundException();
        }

        return $taxon;
    }
}
