<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout;

use Gls\GlsPoland\PrestaShop\Helper\CarrierFinder;

/**
 * @mixin CheckoutInterface
 */
trait CarriersByDeliveryOptionFinderTrait
{
    /**
     * @var CarrierFinder
     */
    private $carrierFinder;

    protected function getCarriersByDeliveryOption(\Cart $cart, array $deliveryOption): array
    {
        $carrierIds = $this->getCarrierIdsFromDeliveryOption($cart, $deliveryOption);

        return $this->carrierFinder->findByCarrierIds(...$carrierIds);
    }

    protected function getCarrierIdsFromDeliveryOption(\Cart $cart, array $deliveryOption): array
    {
        $addressId = (int) $cart->id_address_delivery;

        if (!isset($deliveryOption[$addressId])) {
            return [];
        }

        $carrierIdsList = trim($deliveryOption[$addressId], ',');

        return array_map('intval', explode(',', $carrierIdsList));
    }
}
