<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Delivery;

use InPost\International\Delivery\AvailabilityChecker\CarrierAvailabilityCheckerInterface;
use InPost\International\Delivery\Calculator\IndependentShippingCostCalculatorInterface;
use InPost\International\Delivery\Calculator\ShippingCostCalculatorInterface;
use InPost\International\Delivery\Exception\DeliveryUnavailableException;
use InPost\International\Delivery\Util\CarrierFinder;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ShippingCostCalculationHandler implements ShippingCostCalculationHandlerInterface
{
    /**
     * @var CarrierFinder
     */
    private $carrierFinder;

    /**
     * @var CarrierAvailabilityCheckerInterface
     */
    private $availabilityChecker;

    /**
     * @var ShippingCostCalculatorInterface
     */
    private $calculator;

    public function __construct(CarrierFinder $carrierFinder, CarrierAvailabilityCheckerInterface $availabilityChecker, ShippingCostCalculatorInterface $calculator)
    {
        $this->carrierFinder = $carrierFinder;
        $this->availabilityChecker = $availabilityChecker;
        $this->calculator = $calculator;
    }

    /**
     * {@inheritDoc}
     */
    public function getShippingCost(ShippingCostCalculationParameters $params): float
    {
        $shippingCost = $params->getShippingCost();

        if (null === $shippingCost && !$this->calculator instanceof IndependentShippingCostCalculatorInterface) {
            throw new DeliveryUnavailableException('Shipping cost calculation requires the core price calculation result.');
        }

        if (null === $carrier = $this->carrierFinder->findOneByCarrierId($params->getCarrierId())) {
            throw new DeliveryUnavailableException('Carrier not found.');
        }

        $cart = $params->getCart();

        if (!$this->availabilityChecker->isAvailable($carrier, $cart)) {
            throw new DeliveryUnavailableException('Carrier is unavailable for the given cart.');
        }

        return $this->calculator->calculate($cart, $carrier, $shippingCost);
    }
}
