<?php

namespace Tests\Feature;

use App\Livewire\Servers\Show;
use App\Models\Server;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class ServerShowPanelsTest extends TestCase
{
    use RefreshDatabase;

    private function server(): Server
    {
        return Server::create(['name' => 's', 'ip' => '10.0.0.9', 'ssh_port' => 22, 'status' => 'online']);
    }

    public function test_firewall_and_fail2ban_panels_hidden_when_not_installed(): void
    {
        $this->actingAs(User::factory()->create());

        Livewire::test(Show::class, ['server' => $this->server()])
            ->set('ready', true)
            ->set('firewall', ['supported' => true, 'installed' => false])
            ->set('fail2ban', ['supported' => true, 'installed' => false])
            ->assertDontSee(__('servers.firewall_title'))
            ->assertDontSee(__('servers.fail2ban_title'));
    }

    public function test_both_panels_shown_when_installed(): void
    {
        $this->actingAs(User::factory()->create());

        Livewire::test(Show::class, ['server' => $this->server()])
            ->set('ready', true)
            ->set('firewall', ['supported' => true, 'installed' => true, 'active' => true, 'tool' => 'ufw', 'manageable' => true, 'rules' => [], 'defaults' => []])
            ->set('fail2ban', ['supported' => true, 'installed' => true, 'active' => true, 'jails' => [], 'ignoreip' => []])
            ->assertSee(__('servers.firewall_title'))
            ->assertSee(__('servers.fail2ban_title'));
    }

    public function test_panel_stays_visible_on_read_error_even_when_not_installed(): void
    {
        // A failed privileged read reports installed=false + readError=true; it must
        // stay visible so the operator can tell "probe failed" from "tool absent".
        $this->actingAs(User::factory()->create());

        Livewire::test(Show::class, ['server' => $this->server()])
            ->set('ready', true)
            ->set('firewall', ['supported' => true, 'installed' => false, 'readError' => true])
            ->set('fail2ban', ['supported' => true, 'installed' => false, 'readError' => true])
            ->assertSee(__('servers.firewall_title'))
            ->assertSee(__('servers.firewall_read_error'))
            ->assertSee(__('servers.fail2ban_title'))
            ->assertSee(__('servers.fail2ban_read_error'));
    }

    public function test_pending_server_header_uses_localized_label(): void
    {
        $this->actingAs(User::factory()->create());
        $server = Server::create(['name' => 's', 'ip' => '10.0.0.9', 'ssh_port' => 22, 'status' => 'pending']);

        Livewire::test(Show::class, ['server' => $server])
            ->assertSee(__('servers.status_pending'))
            ->assertDontSee('Pending');
    }
}
