<?php

namespace Tests\Feature;

use App\Livewire\Modals\CreateServer;
use App\Models\Server;
use App\Models\User;
use App\Services\FleetService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use Tests\TestCase;

class CreateServerTest extends TestCase
{
    use RefreshDatabase;

    private function form(Testable $c): Testable
    {
        return $c->set('name', 'web-1')->set('ip', '10.0.0.5')->set('sshPort', 22)
            ->set('username', 'root')->set('authType', 'password')->set('secret', 'pw');
    }

    public function test_bad_ssh_blocks_creation_and_rolls_back(): void
    {
        $this->actingAs(User::factory()->create());
        $this->mock(FleetService::class, fn ($m) => $m->shouldReceive('testConnection')->andReturn(['ok' => false, 'error' => 'auth failed']));

        $this->form(Livewire::test(CreateServer::class))->call('save')->assertHasErrors('secret');

        $this->assertSame(0, Server::count());
    }

    public function test_good_ssh_creates_server_as_pending(): void
    {
        $this->actingAs(User::factory()->create());
        $this->mock(FleetService::class, fn ($m) => $m->shouldReceive('testConnection')->andReturn(['ok' => true, 'error' => null]));

        $this->form(Livewire::test(CreateServer::class))->call('save')->assertHasNoErrors();

        $this->assertSame(1, Server::count());
        $this->assertSame('pending', Server::first()->status);
    }
}
