<?php

declare(strict_types=1);

namespace Autogedal\Reduceri\Controller\Category;

use Autogedal\Reduceri\Model\ReduceriState;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Helper\Category as CategoryHelper;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Session as CatalogSession;
use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Framework\Registry;
use Magento\Framework\View\Page\Config as PageConfig;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;

class View implements HttpGetActionInterface
{
    public function __construct(
        private readonly RequestInterface            $request,
        private readonly PageFactory                 $pageFactory,
        private readonly RedirectFactory             $redirectFactory,
        private readonly CategoryRepositoryInterface $categoryRepository,
        private readonly CategoryHelper              $categoryHelper,
        private readonly Resolver                    $layerResolver,
        private readonly Registry                    $registry,
        private readonly PageConfig                  $pageConfig,
        private readonly CatalogSession              $catalogSession,
        private readonly StoreManagerInterface       $storeManager,
        private readonly EventManager                $eventManager,
        private readonly CategoryUrlPathGenerator    $categoryUrlPathGenerator,
        private readonly ReduceriState               $reduceriState,
    ) {}

    public function execute(): ResultInterface
    {
        $categoryId = (int) $this->request->getParam('id');
        $storeId    = (int) $this->storeManager->getStore()->getId();

        try {
            $category = $this->categoryRepository->get($categoryId, $storeId);
        } catch (\Exception $e) {
            return $this->redirectFactory->create()->setPath('/');
        }

        if (!$this->categoryHelper->canShow($category)) {
            return $this->redirectFactory->create()->setPath('/');
        }

        // Required by native catalog blocks (Catalog\Block\Category\View, Catalog\Helper\Data)
        $this->registry->register('current_category', $category, true);

        // Module-owned state — replaces deprecated registry('reduceri_category_view')
        $this->reduceriState->setIsCategoryView(true);
        $this->reduceriState->setCategory($category);

        $this->catalogSession->setLastVisitedCategoryId($category->getId());

        // Must be called before any block accesses Layer::getProductCollection()
        $this->layerResolver->create(Resolver::CATALOG_LAYER_CATEGORY);

        $this->eventManager->dispatch('catalog_controller_category_init_after', [
            'category'          => $category,
            'controller_action' => $this,
        ]);

        $resultPage = $this->pageFactory->create();

        $resultPage->addHandle('catalog_category_view');
        $resultPage->addHandle('catalog_category_view_type_layered');
        $resultPage->addHandle('catalog_category_view_id_' . $category->getId());

        $this->pageConfig
            ->addBodyClass('catalog-category-view')
            ->addBodyClass('page-products')
            ->addBodyClass('categorypath-' . $this->categoryUrlPathGenerator->getUrlPath($category))
            ->addBodyClass('category-' . $category->getUrlKey());

        $this->pageConfig->setMetadata('robots', 'NOINDEX,NOFOLLOW');
        $this->pageConfig->getTitle()->set($category->getName() . ' - Reduceri');

        return $resultPage;
    }
}
