<?php

declare(strict_types=1);

namespace Tests\Feature\Middleware;

use App\Http\Middleware\EnsureCentralDomain;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Tests\TestCase;

class EnsureCentralDomainTest extends TestCase
{
    private EnsureCentralDomain $middleware;

    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();
        $this->middleware = new EnsureCentralDomain();
    }

    public function testAllowsRequestWhoseHostMatchesBareEntry(): void
    {
        config(['tenancy.central_domains' => ['my.autonomy.mtcserver.com']]);

        $response = $this->middleware->handle(
            Request::create('https://my.autonomy.mtcserver.com/api/user', 'GET'),
            fn () => response('ok')
        );

        $this->assertSame(200, $response->getStatusCode());
    }

    public function testAllowsRequestWhoseHostMatchesSchemePrefixedEntry(): void
    {
        config(['tenancy.central_domains' => ['https://my.getautonomy.co.uk']]);

        $response = $this->middleware->handle(
            Request::create('https://my.getautonomy.co.uk/api/user', 'GET'),
            fn () => response('ok')
        );

        $this->assertSame(200, $response->getStatusCode());
    }

    public function testAllowsLoopbackAndLocalhostEntries(): void
    {
        config(['tenancy.central_domains' => ['127.0.0.1', 'localhost']]);

        $loopback = $this->middleware->handle(
            Request::create('http://127.0.0.1/api/user', 'GET'),
            fn () => response('ok')
        );
        $localhost = $this->middleware->handle(
            Request::create('http://localhost/api/user', 'GET'),
            fn () => response('ok')
        );

        $this->assertSame(200, $loopback->getStatusCode());
        $this->assertSame(200, $localhost->getStatusCode());
    }

    public function testAbortsWhenHostNotInCentralDomains(): void
    {
        config(['tenancy.central_domains' => ['my.getautonomy.co.uk']]);

        $this->expectException(NotFoundHttpException::class);

        $this->middleware->handle(
            Request::create('https://tenant.example.com/api/user', 'GET'),
            fn () => response('ok')
        );
    }
}
