<?php
declare(strict_types=1);

namespace App\Modules\Shipments;

use App\Modules\Settings\AllegroApiClient;
use App\Modules\Settings\AllegroTokenManager;
use Throwable;

final class AllegroTrackingService implements ShipmentTrackingInterface
{
    public function __construct(
        private readonly AllegroApiClient $apiClient,
        private readonly AllegroTokenManager $tokenManager
    ) {
    }

    public function supports(string $provider): bool
    {
        return $provider === 'allegro_wza';
    }

    public function getDeliveryStatus(array $package): ?array
    {
        $shipmentId = trim((string) ($package['shipment_id'] ?? ''));
        if ($shipmentId === '') {
            return null;
        }

        return $this->fetchStatus($shipmentId);
    }

    private function fetchStatus(string $shipmentId): ?array
    {
        try {
            [$accessToken, $env] = $this->tokenManager->resolveToken();
            $details = $this->apiClient->getShipmentDetails($env, $accessToken, $shipmentId);

            $rawStatus = strtoupper(trim((string) ($details['status'] ?? '')));
            if ($rawStatus === '') {
                return null;
            }

            return [
                'status' => DeliveryStatus::normalize('allegro_wza', $rawStatus),
                'status_raw' => $rawStatus,
                'description' => DeliveryStatus::description('allegro_wza', $rawStatus),
            ];
        } catch (Throwable) {
            return null;
        }
    }
}
