<?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 Doctrine\ORM\EntityRepository;
use InPost\International\Delivery\Point\PointDataProviderInterface;
use InPost\International\Delivery\Point\PointInterface;
use InPost\International\Delivery\Point\Presenter\PointPresenterInterface;
use PrestaShopBundle\Entity\Lang;

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

/**
 * @internal
 */
final class MailHelper
{
    /**
     * @var OrderHelper
     */
    private $orderHelper;

    /**
     * @var PointDataProviderInterface
     */
    private $pointDataProvider;

    /**
     * @var PointPresenterInterface
     */
    private $pointPresenter;

    /**
     * @var EntityRepository<Lang>
     */
    private $languageRepository;

    /**
     * @param EntityRepository<Lang> $languageRepository
     */
    public function __construct(OrderHelper $orderHelper, PointDataProviderInterface $pointDataProvider, PointPresenterInterface $pointPresenter, EntityRepository $languageRepository)
    {
        $this->orderHelper = $orderHelper;
        $this->pointDataProvider = $pointDataProvider;
        $this->pointPresenter = $pointPresenter;
        $this->languageRepository = $languageRepository;
    }

    public function getPointNameByOrderId(int $orderId, int $languageId): ?string
    {
        if (null === $pointId = $this->orderHelper->getDeliveryPointIdByOrderId($orderId)) {
            return null;
        }

        if (null === $point = $this->getPoint($pointId)) {
            return null;
        }

        $locale = $this->getLocale($languageId);

        return $this->pointPresenter->formatName($point, $locale);
    }

    public function getPointAddressByOrderReference(string $orderReference, int $languageId): ?string
    {
        if (null === $pointId = $this->orderHelper->getDeliveryPointIdByOrderReference($orderReference)) {
            return null;
        }

        if (null === $point = $this->getPoint($pointId)) {
            return null;
        }

        $locale = $this->getLocale($languageId);

        return $this->pointPresenter->formatAddress($point, $locale);
    }

    private function getPoint(string $pointId): ?PointInterface
    {
        try {
            return $this->pointDataProvider->getPoint($pointId);
        } catch (\Exception $e) {
            return null;
        }
    }

    private function getLocale(int $languageId): ?string
    {
        if (null === $language = $this->languageRepository->find($languageId)) {
            return null;
        }

        return $language->getLocale();
    }
}
