<?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\AvailabilityChecker;

use InPost\International\Delivery\Util\DeliveryCountryResolver;
use InPost\International\Entity\Carrier;

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

final class ProductWeightChecker implements CarrierAvailabilityCheckerInterface
{
    /**
     * @var DeliveryCountryResolver
     */
    private $resolver;

    public function __construct(DeliveryCountryResolver $resolver)
    {
        $this->resolver = $resolver;
    }

    public function isAvailable(Carrier $carrier, \Cart $cart): bool
    {
        $maxWeight = $this->getMaxWeight($cart, $carrier);

        foreach ($cart->getProducts() as $product) {
            if ($maxWeight < (float) $product['weight']) {
                return false;
            }
        }

        return true;
    }

    private function getMaxWeight(\Cart $cart, Carrier $carrier): float
    {
        if (null !== $country = $this->resolver->resolve($cart)) {
            return $carrier->getType()->getMaxParcelWeight($country);
        }

        $maxWeights = array_map([$carrier->getType(), 'getMaxParcelWeight'], $carrier->getCountries());

        return max($maxWeights);
    }
}
