<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\Model\QuoteRepository;

use Exception;
use FiloBlu\Refilo\Model\ShippingEstimationResolverInterface;
use Magento\Quote\Api\Data\CartInterface;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 * @see \Magento\Quote\Model\QuoteRepository\LoadHandler
 */
class LoadHandler
{
    /**
     * @var \FiloBlu\Refilo\Model\ShippingEstimationResolverInterface
     */
    private $estimationResolver;
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    /**
     * @param \FiloBlu\Refilo\Model\ShippingEstimationResolverInterface $estimationResolver
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(ShippingEstimationResolverInterface $estimationResolver, LoggerInterface $logger)
    {
        $this->estimationResolver = $estimationResolver;
        $this->logger = $logger;
    }

    /**
     * @throws Exception
     * @see \Magento\Quote\Model\QuoteRepository\LoadHandler::load
     *
     */
    public function afterLoad(\Magento\Quote\Model\QuoteRepository\LoadHandler $subject, CartInterface $quote)
    {
        if (
            !$quote->getIsActive() || !$quote->hasItems() || !$this->estimationResolver->hasStrategyForStore(
                $quote->getStoreId()
            )
        ) {
            return $quote;
        }

        try {
            return $this->estimationResolver->getByStore($quote->getStoreId())->estimate($quote);
        } catch (Throwable $throwable) {
            $this->logger->error($throwable->getMessage(), ['exception' => $throwable]);
        }

        return $quote;
    }
}
