<?php

namespace App\Livewire\Servers;

use App\Models\Server;
use App\Models\ServerGroup;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.app')]
class Index extends Component
{
    /** Live search over name / IP. */
    public string $search = '';

    /** Optional group filter (a ServerGroup uuid, shareable via the query string). */
    #[Url]
    public ?string $group = null;

    /** Page <title>; localized at runtime (attributes can't call __()). */
    public function title(): string
    {
        return __('servers.index_title');
    }

    /** A freshly added server should appear without a manual reload (render() re-queries). */
    #[On('serverCreated')]
    public function refreshServers(): void
    {
        //
    }

    public function render(): View
    {
        $term = trim($this->search);

        // Resolve the group filter; an unknown/removed uuid falls back to "all" (never errors).
        $activeGroup = $this->group ? ServerGroup::where('uuid', $this->group)->first() : null;

        $servers = Server::orderBy('name')
            ->when($activeGroup, fn ($query) => $query->inGroup($activeGroup->id))
            ->when($term !== '', function ($query) use ($term) {
                $query->where(function ($q) use ($term) {
                    $q->where('name', 'like', "%{$term}%")
                        ->orWhere('ip', 'like', "%{$term}%");
                });
            })
            ->get();

        // Totals reflect the whole fleet, not the filtered result.
        $counts = Server::query()
            ->selectRaw('status, count(*) as total')
            ->groupBy('status')
            ->pluck('total', 'status');

        return view('livewire.servers.index', [
            'servers' => $servers,
            'groups' => ServerGroup::withCount('servers')->orderBy('name')->get(),
            'activeGroup' => $activeGroup,
            'total' => (int) $counts->sum(),
            'online' => (int) ($counts['online'] ?? 0),
            'warning' => (int) ($counts['warning'] ?? 0),
            'offline' => (int) ($counts['offline'] ?? 0),
        ])->title($this->title());
    }
}
