<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Controller\Ajax;

use Amasty\JetTheme\Model\Product\HoverImageProvider;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
use Psr\Log\LoggerInterface;

class GetHoverImages extends Action implements HttpPostActionInterface
{

    /**
     * @var HoverImageProvider
     */
    private $hoverImageProvider;

    /**
     * @var ProductRepository
     */
    private $productRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        Context $context,
        HoverImageProvider $hoverImageProvider,
        ProductRepository $productRepository,
        LoggerInterface $logger
    ) {
        parent::__construct($context);
        $this->hoverImageProvider = $hoverImageProvider;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
    }

    public function execute(): ResultInterface
    {
        /** @var Json $resultJson */
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $productId = $this->getRequest()->getParam('product_id');

        try {
            $product = $this->productRepository->getById((int)$productId);
            $resultJson->setData($this->hoverImageProvider->getHoverImages($product));
        } catch (\Exception $e) {
            $resultJson->setData(['error' => true]);
            $this->logger->critical($e);
        }

        return $resultJson;
    }
}
