<?php

namespace Tests\Feature;

use App\Services\DeploymentService;
use App\Services\WebauthnService;
use Illuminate\Http\Request;
use Tests\TestCase;

class WebauthnAvailableTest extends TestCase
{
    private function service(?string $domain, string $host = 'panel.example.com'): WebauthnService
    {
        $deployment = $this->mock(DeploymentService::class);
        $deployment->shouldReceive('domain')->andReturn($domain);
        // The bound request decides the host WebAuthn availability keys on.
        app()->instance('request', Request::create('http://'.$host.'/settings/security'));

        return app(WebauthnService::class);
    }

    public function test_available_when_reached_via_the_active_domain_even_over_plain_http(): void
    {
        // External-proxy mode: the request looks like plain HTTP here, but the browser context is
        // secure (the proxy serves HTTPS). Host == active domain → hardware keys are available.
        $this->assertTrue($this->service('panel.example.com', 'panel.example.com')->available());
    }

    public function test_unavailable_without_a_domain(): void
    {
        $this->assertFalse($this->service(null, 'panel.example.com')->available());
    }

    public function test_unavailable_on_the_bare_ip_recovery_host(): void
    {
        // Reached via the IP recovery path (plain HTTP, no secure context) → locked even with a
        // domain configured; the rpId would not match the IP origin anyway.
        $this->assertFalse($this->service('panel.example.com', '10.0.0.5')->available());
    }
}
