<?php

namespace Tests\Unit\Tenant;

use App\Domains\Tenant\Support\TenantDomainNormalizer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class TenantDomainNormalizerTest extends TestCase
{
    #[DataProvider('tenantKeys')]
    public function test_it_normalizes_a_hostname_and_path_as_a_single_tenant_key(
        string $domain,
        ?string $path,
        string $expected,
    ): void {
        $this->assertSame(
            $expected,
            TenantDomainNormalizer::normalizeTenantKey($domain, $path),
        );
    }

    /** @return iterable<string, array{string, ?string, string}> */
    public static function tenantKeys(): iterable
    {
        yield 'pura tendencia' => [
            'QA.ONTICKET.COM.AR',
            '/puratendencia',
            'qa.onticket.com.ar/puratendencia',
        ];

        yield 'sonder with trailing slash' => [
            'qa.onticket.com.ar',
            '/sonder/',
            'qa.onticket.com.ar/sonder',
        ];

        yield 'root tenant' => [
            'fnfi.onticket.com.ar',
            '/',
            'fnfi.onticket.com.ar',
        ];

        yield 'full tenant URL when storing' => [
            'https://QA.ONTICKET.COM.AR/puratendencia/',
            null,
            'qa.onticket.com.ar/puratendencia',
        ];
    }

    public function test_it_builds_tenant_key_candidates_from_the_longest_path_to_the_root(): void
    {
        $this->assertSame([
            'qa.onticket.com.ar/puratendencia/vip/productos/123',
            'qa.onticket.com.ar/puratendencia/vip/productos',
            'qa.onticket.com.ar/puratendencia/vip',
            'qa.onticket.com.ar/puratendencia',
            'qa.onticket.com.ar',
        ], TenantDomainNormalizer::tenantKeyCandidates(
            'QA.ONTICKET.COM.AR',
            '/puratendencia/vip/productos/123?ref=home',
        ));
    }

    public function test_tenant_key_candidates_only_include_complete_path_segments(): void
    {
        $this->assertSame([
            'qa.onticket.com.ar/sonder-shop/productos',
            'qa.onticket.com.ar/sonder-shop',
            'qa.onticket.com.ar',
        ], TenantDomainNormalizer::tenantKeyCandidates(
            'qa.onticket.com.ar',
            '/sonder-shop/productos',
        ));
    }

    public function test_it_builds_base_path_candidates_from_the_longest_path_to_root(): void
    {
        $this->assertSame([
            '/desfile/productos/123',
            '/desfile/productos',
            '/desfile',
            '/',
        ], TenantDomainNormalizer::basePathCandidates('/desfile/productos/123?ref=home'));
    }
}
