<?php

namespace App\Livewire\Concerns;

use App\Models\Server;
use Illuminate\Support\Collection;

/**
 * Shared fleet context for pages: the active server plus the whole fleet.
 * Without an explicit session selection we prefer a reachable (credentialed,
 * non-offline) server so pages land on a box that returns real SSH data.
 */
trait WithFleetContext
{
    public function fleet(): Collection
    {
        return Server::withExists('credential')->orderBy('name')->get();
    }

    public function activeServer(): ?Server
    {
        $fleet = $this->fleet();

        return $fleet->firstWhere('id', session('active_server_id'))
            ?? $fleet->first(fn (Server $s) => $s->credential_exists && $s->status !== 'offline')
            ?? $fleet->firstWhere('status', 'online')
            ?? $fleet->first();
    }
}
