<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model;

use Exception;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

/**
 *
 */
class ShippingEstimationResolver implements ShippingEstimationResolverInterface
{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;
    /**
     * @var ShippingEstimationStrategyInterface[]
     */
    private $shipmentStrategies;

    /**
     * @var string
     */
    private $configurationPath;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param string $configurationPath
     * @param array $shipmentStrategies
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        string $configurationPath,
        array $shipmentStrategies = []
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->shipmentStrategies = $shipmentStrategies;
        $this->configurationPath = $configurationPath;
    }

    /**
     * @param int|string $store
     * @return \FiloBlu\Refilo\Model\ShippingEstimationStrategyInterface
     * @throws \Exception
     */
    public function getByStore($store): ShippingEstimationStrategyInterface
    {
        if (!$this->hasStrategyForStore($store)) {
            throw new Exception('Unable to find shipping strategy');
        }

        return $this->shipmentStrategies[$this->scopeConfig->getValue($this->configurationPath, ScopeInterface::SCOPE_STORE, $store)];
    }

    /**
     * @param $store
     * @return bool
     */
    public function hasStrategyForStore($store): bool
    {
        $strategy = $this->scopeConfig->getValue($this->configurationPath, ScopeInterface::SCOPE_STORE, $store);

        return ($strategy && isset($this->shipmentStrategies[$strategy]));
    }

    /**
     * @return array|\FiloBlu\Refilo\Model\ShippingEstimationStrategyInterface[]
     */
    public function getAll(): array
    {
        return $this->shipmentStrategies;
    }
}
