<?php
/**
 * Copyright © Banyo. All rights reserved.
 */

namespace Banyo\CheckoutFix\Plugin\Review\Block;

use Magento\Review\Block\Form;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Message\ManagerInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ProductFactory;
use Psr\Log\LoggerInterface;

class FormPlugin
{
    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @var ProductFactory
     */
    protected $productFactory;

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

    /**
     * @param ManagerInterface $messageManager
     * @param ProductFactory $productFactory
     * @param LoggerInterface $logger
     */
    public function __construct(
        ManagerInterface $messageManager,
        ProductFactory $productFactory,
        LoggerInterface $logger
    ) {
        $this->messageManager = $messageManager;
        $this->productFactory = $productFactory;
        $this->logger = $logger;
    }

    /**
     * Around plugin for getProductInfo method
     *
     * @param Form $subject
     * @param \Closure $proceed
     * @return ProductInterface
     */
    public function aroundGetProductInfo(Form $subject, \Closure $proceed)
    {
        try {
            // Try to execute the original method
            return $proceed();
        } catch (NoSuchEntityException $e) {
            // Log the exception
            $this->logger->error('Review form error: ' . $e->getMessage(), [
                'product_id' => $subject->getRequest()->getParam('id', false),
                'exception' => $e
            ]);

            // Check if we're on a cart page before adding the error message
            $request = $subject->getRequest();
            $fullActionName = $request->getFullActionName();

            // Only add the error message if we're not on a cart page
            if (strpos($fullActionName, 'checkout_cart') === false) {
                // Add a friendly message to the user
                $this->messageManager->addErrorMessage(
                    __('The product you are trying to review is no longer available. Please contact customer support for assistance.')
                );
            }

            // Return a dummy product object to prevent template errors
            $product = $this->productFactory->create();
            $product->setName(__('Product Not Available'));

            return $product;
        }
    }
}
