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

use InPost\International\Checkout\CheckoutSessionRepository;
use InPost\International\Delivery\Util\CarrierFinder;
use InPost\International\Entity\PointDeliveryCarrier;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;

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

final class OrderHelper
{
    /**
     * @var ObjectRepositoryInterface<\Order>
     */
    private $orderRepository;

    /**
     * @var CarrierFinder
     */
    private $carrierFinder;

    /**
     * @var CheckoutSessionRepository
     */
    private $sessionRepository;

    /**
     * @param ObjectRepositoryInterface<\Order> $orderRepository
     */
    public function __construct(ObjectRepositoryInterface $orderRepository, CarrierFinder $carrierFinder, CheckoutSessionRepository $sessionRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->carrierFinder = $carrierFinder;
        $this->sessionRepository = $sessionRepository;
    }

    public function getDeliveryPointId(\Order $order): ?string
    {
        $carrier = $this->carrierFinder->findOneByCarrierId((int) $order->id_carrier);

        if (!$carrier instanceof PointDeliveryCarrier) {
            return null;
        }

        if (null === $session = $this->sessionRepository->find((int) $order->id_cart)) {
            return null;
        }

        return $session->getPointId($carrier->getReferenceId());
    }

    public function getDeliveryPointIdByOrderId(int $orderId): ?string
    {
        if (null === $order = $this->orderRepository->find($orderId)) {
            return null;
        }

        return $this->getDeliveryPointId($order);
    }

    public function getDeliveryPointIdByOrderReference(string $reference): ?string
    {
        $orders = $this->orderRepository->findBy(['reference' => $reference]);

        if (1 !== count($orders)) {
            return null;
        }

        return $this->getDeliveryPointId($orders[0]);
    }
}
