<?php

namespace Tests\Feature;

use App\Livewire\System\Index;
use App\Models\User;
use App\Services\DeploymentService;
use App\Support\Confirm\ConfirmToken;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class TlsModeToggleTest extends TestCase
{
    use RefreshDatabase;

    public function test_applying_external_mode_persists_and_flags_restart(): void
    {
        $this->actingAs(User::factory()->create(['must_change_password' => false]));

        $token = ConfirmToken::issue('tlsModeChanged', ['mode' => 'external']);
        ConfirmToken::confirm($token);
        Livewire::test(Index::class)
            ->call('applyTlsMode', $token, app(DeploymentService::class))
            ->assertSet('tlsMode', 'external')
            ->assertSet('restartPending', true);

        $this->assertTrue(app(DeploymentService::class)->externalTls());
    }

    public function test_invalid_mode_is_ignored(): void
    {
        $this->actingAs(User::factory()->create(['must_change_password' => false]));

        $token = ConfirmToken::issue('tlsModeChanged', ['mode' => 'garbage']);
        ConfirmToken::confirm($token);
        Livewire::test(Index::class)
            ->call('applyTlsMode', $token, app(DeploymentService::class))
            ->assertSet('tlsMode', 'caddy');

        $this->assertFalse(app(DeploymentService::class)->externalTls());
    }

    public function test_applying_a_mode_writes_an_audit_event(): void
    {
        $this->actingAs(User::factory()->create(['must_change_password' => false]));

        $token = ConfirmToken::issue('tlsModeChanged', ['mode' => 'external']);
        ConfirmToken::confirm($token);
        Livewire::test(Index::class)
            ->call('applyTlsMode', $token, app(DeploymentService::class));

        $this->assertDatabaseHas('audit_events', [
            'action' => 'system.settings_updated',
            'target' => 'tls_mode=external',
        ]);
    }
}
