<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Controller;

use Autogedal\Manufacturers\Api\Data\ManufacturerPageInterface;
use Autogedal\Manufacturers\Api\ManufacturerPageRepositoryInterface;
use Autogedal\Manufacturers\Model\Config;
use Autogedal\Manufacturers\Model\ManufacturerUrl;
use Autogedal\Manufacturers\Service\SlugHandler;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\Forward;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\NoSuchEntityException;

abstract class AbstractManufacturerPage extends Action implements HttpGetActionInterface
{
    public function __construct(
        Context $context,
        private readonly Config $config,
        private readonly ManufacturerPageRepositoryInterface $pageRepository,
        private readonly SlugHandler $slugHandler,
        private readonly ManufacturerUrl $manufacturerUrl
    ) {
        parent::__construct($context);
    }

    protected function getManufacturerPage(): ?ManufacturerPageInterface
    {
        if (!$this->config->isEnabled()) {
            return null;
        }

        $slug = $this->getSlug();
        if (!$this->slugHandler->validateSlug($slug)) {
            return null;
        }

        try {
            $page = $this->pageRepository->getBySlug($slug);
        } catch (NoSuchEntityException) {
            return null;
        }

        return $this->config->isManufacturerActive((int)$page->getOptionId()) ? $page : null;
    }

    protected function getManufacturerUrl(): string
    {
        return $this->manufacturerUrl->getUrl($this->getSlug());
    }

    protected function notFound(): Forward
    {
        return $this->resultFactory->create(ResultFactory::TYPE_FORWARD)->forward('noroute');
    }

    private function getSlug(): string
    {
        return (string)$this->getRequest()->getParam('slug');
    }
}
