<?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\Carrier\Configurator;

use InPost\International\Carrier\CarrierConfiguration;
use InPost\International\Carrier\Message\CreateCarrierCommand;

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

final class PriceRangesConfigurator implements CarrierConfiguratorInterface
{
    public function configure(CarrierConfiguration $configuration, CreateCarrierCommand $command): void
    {
        if (\Carrier::SHIPPING_METHOD_WEIGHT !== $configuration->getCarrier()->getShippingMethod()) {
            return;
        }

        $maxWeight = $configuration->getCarrier()->max_weight ?? self::getMaxWeight($command);

        $range = $this->createWeightRange(0., (float) $maxWeight);
        $configuration->addWeightRange($range);
    }

    private function createWeightRange(float $lower, float $upper): \RangeWeight
    {
        $range = new \RangeWeight();
        $range->delimiter1 = $lower;
        $range->delimiter2 = $upper;

        return $range;
    }

    private static function getMaxWeight(CreateCarrierCommand $command): float
    {
        $maxWeights = array_map([$command->getType(), 'getMaxParcelWeight'], $command->getCountries());

        return max($maxWeights);
    }
}
