<?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\Api\Tracking\Model;

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

final class Parcel
{
    /**
     * @var Event[]
     */
    private $events;

    /**
     * @var Location|null
     */
    private $origin;

    /**
     * @var Location
     */
    private $destination;

    /**
     * @var Delivery
     */
    private $delivery;

    /**
     * @var Shipment
     */
    private $shipment;

    /**
     * @var string
     */
    private $trackingNumber;

    /**
     * @var string|null
     */
    private $status;

    /**
     * @var ReturnToSender|null
     */
    private $returnToSender;

    /**
     * @param Event[] $events
     */
    public function __construct(array $events, Location $destination, Delivery $delivery, Shipment $shipment, string $trackingNumber, Location $origin = null, string $status = null, ReturnToSender $returnToSender = null)
    {
        $this->events = $this->sortEvents($events);
        $this->origin = $origin;
        $this->destination = $destination;
        $this->delivery = $delivery;
        $this->shipment = $shipment;
        $this->trackingNumber = $trackingNumber;
        $this->status = $status;
        $this->returnToSender = $returnToSender;
    }

    /**
     * @return Event[]
     */
    public function getEvents(): array
    {
        return $this->events;
    }

    public function getMostRecentEvent(): Event
    {
        return $this->events[0];
    }

    public function getOrigin(): ?Location
    {
        return $this->origin;
    }

    public function getDestination(): Location
    {
        return $this->destination;
    }

    public function getDelivery(): Delivery
    {
        return $this->delivery;
    }

    public function getShipment(): Shipment
    {
        return $this->shipment;
    }

    public function getTrackingNumber(): string
    {
        return $this->trackingNumber;
    }

    public function getStatus(): ?string
    {
        return $this->status;
    }

    public function getReturnToSender(): ?ReturnToSender
    {
        return $this->returnToSender;
    }

    /**
     * @param Event[] $events
     *
     * @return Event[] events sorted from latest to oldest
     */
    private function sortEvents(array $events): array
    {
        usort($events, static function (Event $a, Event $b): int {
            return $b->getTimestamp() <=> $a->getTimestamp();
        });

        return $events;
    }
}
