<?php

namespace Tests\Feature;

use App\Models\Server;
use App\Services\FleetService;
use App\Services\MaintenanceService;
use App\Support\Os\OsDetector;
use App\Support\Os\OsProfile;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class MaintenanceUpdateCountsTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        Mockery::close();
        parent::tearDown();
    }

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

    private function service(string $runPlainOutput, OsProfile $os): MaintenanceService
    {
        $fleet = Mockery::mock(FleetService::class);
        $fleet->shouldReceive('runPlain')->andReturn(['ok' => true, 'output' => $runPlainOutput]);
        $detector = Mockery::mock(OsDetector::class);
        $detector->shouldReceive('detect')->andReturn($os);

        return new MaintenanceService($fleet, $detector);
    }

    private function apt(): OsProfile
    {
        return new OsProfile('debian', 'debian', 'Debian 13', 'apt', 'ufw', 'systemd', ['apt-get']);
    }

    public function test_parses_pending_and_security_counts(): void
    {
        $counts = $this->service("CLUSEV_OK\nCLUSEV_PENDING=12\nCLUSEV_SECURITY=3", $this->apt())->updateCounts($this->server());

        $this->assertSame(12, $counts['pending']);
        $this->assertSame(3, $counts['security']);
    }

    public function test_security_is_clamped_to_pending(): void
    {
        // A noisy grep could over-count security; it can never exceed the total.
        $counts = $this->service("CLUSEV_OK\nCLUSEV_PENDING=2\nCLUSEV_SECURITY=9", $this->apt())->updateCounts($this->server());

        $this->assertSame(2, $counts['pending']);
        $this->assertSame(2, $counts['security']);
    }

    public function test_missing_sentinel_yields_unknown(): void
    {
        $counts = $this->service('some error, no sentinel', $this->apt())->updateCounts($this->server());

        $this->assertNull($counts['pending']);
        $this->assertNull($counts['security']);
    }

    public function test_unsupported_manager_yields_unknown(): void
    {
        $alpine = new OsProfile('alpine', 'alpine', 'Alpine', 'apk', 'none', 'openrc', []);
        $fleet = Mockery::mock(FleetService::class);
        $fleet->shouldReceive('runPlain')->never(); // never even probes an unsupported manager
        $detector = Mockery::mock(OsDetector::class);
        $detector->shouldReceive('detect')->andReturn($alpine);

        $counts = (new MaintenanceService($fleet, $detector))->updateCounts($this->server());

        $this->assertNull($counts['pending']);
    }
}
