<?php

namespace Tests\Feature;

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

class ServerTerminalTest extends TestCase
{
    use RefreshDatabase;

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

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

        Livewire::test(ServerTerminal::class, ['server' => $server])->call('open')->assertOk();

        $s = TerminalSession::first();
        $this->assertNotNull($s);
        $this->assertSame('server', $s->kind);
        $this->assertSame($server->id, $s->server_id);
        $this->assertNull($s->used_at);
        $this->assertTrue($s->expires_at->isFuture());
    }

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

        Livewire::test(ServerTerminal::class, ['server' => $server])->call('open')->assertForbidden();
        $this->assertSame(0, TerminalSession::count());
    }
}
