<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\Controller;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin\OrderController;
use PHPUnit\Framework\TestCase;

final class OrderTrackingCarrierTest extends TestCase
{
    public function testTrackingCarriersAreCompleteAndSortedAlphabetically(): void
    {
        $carriers = $this->trackingCarriers();

        self::assertSame([
            'DB-Schenker',
            'DHL Express',
            'FedEx',
            'Genin',
            'Geodis',
            'La Poste / Colissimo / Chronopost',
            'Logivin',
            'LTD',
            'Oenotrans',
            'Patrice Antoine',
            'Scellier',
            'TCP',
            'Transvins',
            'UPS',
        ], array_column($carriers, 'label'));
    }

    public function testTrackingUrlIsGeneratedOnlyWhenCarrierSupportsIt(): void
    {
        $reflection = new \ReflectionClass(OrderController::class);
        $controller = $reflection->newInstanceWithoutConstructor();
        $buildTrackingUrl = $reflection->getMethod('buildTrackingUrl');

        self::assertSame(
            'https://www.ups.com/track?loc=fr_FR&tracknum=ABC%20123',
            $buildTrackingUrl->invoke($controller, 'ups', 'ABC 123'),
        );
        self::assertNull($buildTrackingUrl->invoke($controller, 'transvins', 'ABC 123'));
    }

    /**
     * @return array<string, array{label: string, url_template: ?string}>
     */
    private function trackingCarriers(): array
    {
        $constant = (new \ReflectionClass(OrderController::class))->getReflectionConstant('TRACKING_CARRIERS');

        self::assertInstanceOf(\ReflectionClassConstant::class, $constant);

        /** @var array<string, array{label: string, url_template: ?string}> $carriers */
        $carriers = $constant->getValue();

        return $carriers;
    }
}
