<?php
declare(strict_types=1);

namespace Autogedal\Helper\Plugin;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Mageplaza\ProductAttachments\Controller\File\ViewOnline;

class ProductAttachmentsViewOnline
{
    public function __construct(
        private readonly ProductRepositoryInterface $productRepository,
        private readonly ResultFactory $resultFactory
    ) {
    }

    public function aroundExecute(ViewOnline $subject, callable $proceed)
    {
        $productId = (int) $subject->getRequest()->getParam('product_id');

        if ($productId <= 0) {
            return $this->noRouteResult();
        }

        try {
            $this->productRepository->getById($productId);
        } catch (NoSuchEntityException $exception) {
            return $this->noRouteResult();
        }

        return $proceed();
    }

    private function noRouteResult()
    {
        return $this->resultFactory
            ->create(ResultFactory::TYPE_REDIRECT)
            ->setPath('no-route');
    }
}
