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

use InPost\International\Carrier\CarrierRepositoryInterface;
use InPost\International\Entity\Carrier;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;

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

class CarrierFinder
{
    /**
     * @var CarrierRepositoryInterface
     */
    private $repository;

    /**
     * @var ObjectRepositoryInterface<\Carrier>
     */
    private $objectModelRepository;

    /**
     * @var array<int, Carrier|null>
     */
    private $carriersById = [];

    /**
     * @param ObjectRepositoryInterface<\Carrier> $objectModelRepository
     */
    public function __construct(CarrierRepositoryInterface $repository, ObjectRepositoryInterface $objectModelRepository)
    {
        $this->repository = $repository;
        $this->objectModelRepository = $objectModelRepository;
    }

    /**
     * @param int $carrierId native {@see \Carrier} identifier
     */
    public function findOneByCarrierId(int $carrierId): ?Carrier
    {
        if (0 >= $carrierId) {
            return null;
        }

        if (array_key_exists($carrierId, $this->carriersById)) {
            return $this->carriersById[$carrierId];
        }

        if (null === $carrier = $this->objectModelRepository->find($carrierId)) {
            return $this->carriersById[$carrierId] = null;
        }

        return $this->carriersById[$carrierId] = $this->repository->find((int) $carrier->id_reference);
    }

    /**
     * @param array<int, string> $deliveryOption comma separated lists of {@see \Carrier} IDs by address ID
     *
     * @return Carrier[]
     */
    public function findByDeliveryOption(array $deliveryOption): array
    {
        $carrierIds = $this->getCarrierIds($deliveryOption);

        return array_map([$this, 'findOneByCarrierId'], $carrierIds);
    }

    /**
     * @return int[]
     */
    private function getCarrierIds(array $deliveryOption): array
    {
        $carrierIdsByAddressId = array_map([$this, 'parseCarrierList'], $deliveryOption);

        return array_unique(array_merge(...$carrierIdsByAddressId));
    }

    /**
     * @return int[] carrier IDs
     */
    private function parseCarrierList(string $carrierList): array
    {
        $carrierIds = explode(',', trim($carrierList, ','));

        return array_map('intval', $carrierIds);
    }
}
