<?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\Checkout\View\Builder;

use InPost\International\Checkout\CheckoutSessionRepositoryInterface;
use InPost\International\Checkout\View\Model\CheckoutView;
use InPost\International\Checkout\View\Model\SelectedPointView;
use InPost\International\Delivery\Point\PointDataProviderInterface;

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

final class SelectedPointViewBuilder implements CheckoutViewBuilderInterface
{
    /**
     * @var CheckoutSessionRepositoryInterface
     */
    private $sessionRepository;

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

    public function __construct(CheckoutSessionRepositoryInterface $sessionRepository, PointDataProviderInterface $pointDataProvider)
    {
        $this->sessionRepository = $sessionRepository;
        $this->pointDataProvider = $pointDataProvider;
    }

    public function buildView(CheckoutView $view): void
    {
        $cart = $view->getCart();

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

        $referenceId = $view->getCarrier()->getReferenceId();

        if (null === $pointId = $session->getPointId($referenceId)) {
            return;
        }

        try {
            $point = $this->pointDataProvider->getPoint($pointId);
        } catch (\Exception $e) {
            return;
        }

        if (null === $point) {
            return;
        }

        $view->setSelectedPoint(new SelectedPointView($point));
    }
}
