<?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\Shipment\MessageHandler;

use InPost\International\Api\Exception\ApiClientExceptionInterface;
use InPost\International\Api\Tracking\Model\Parcel;
use InPost\International\Api\Tracking\TrackingApiClientInterface;
use InPost\International\Shipment\Exception\ShipmentNotFoundException;
use InPost\International\Shipment\Message\GetTrackingDetailsCommand;
use InPost\International\Shipment\ShipmentRepositoryInterface;

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

final class GetTrackingDetailsHandler
{
    /**
     * @var ShipmentRepositoryInterface
     */
    private $repository;

    /**
     * @var TrackingApiClientInterface
     */
    private $client;

    public function __construct(ShipmentRepositoryInterface $repository, TrackingApiClientInterface $client)
    {
        $this->repository = $repository;
        $this->client = $client;
    }

    /**
     * @throws ShipmentNotFoundException
     * @throws ApiClientExceptionInterface
     */
    public function __invoke(GetTrackingDetailsCommand $command): ?Parcel
    {
        if (null === $shipment = $this->repository->find($command->getShipmentId())) {
            throw ShipmentNotFoundException::create($command->getShipmentId());
        }

        $trackingNumber = $shipment->getTrackingNumber();

        return $this->client->getTrackingDetails($trackingNumber)->getParcel($trackingNumber);
    }

    public function handle(GetTrackingDetailsCommand $command): ?Parcel
    {
        return ($this)($command);
    }
}
