<?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
{
    /**
     * Per-request memo. activeServer() calls fleet() and is itself called several times per
     * render (Files ~6x, Services ~4x), so without this each call re-ran the fleet query.
     * Protected, so Livewire does not serialise it into the snapshot; it resets on every
     * request (the component is re-hydrated), and no page in scope mutates the fleet mid-request.
     */
    protected ?Collection $fleetMemo = null;

    public function fleet(): Collection
    {
        return $this->fleetMemo ??= 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();
    }
}
