<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Str;

class Server extends Model
{
    protected $guarded = [];

    protected $casts = [
        'specs' => 'array',
        'last_seen_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(fn (self $s) => $s->uuid ??= (string) Str::uuid());
    }

    // R11: URLs address servers by uuid, never the bigint id.
    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function credential(): HasOne
    {
        return $this->hasOne(SshCredential::class);
    }

    public function groups(): BelongsToMany
    {
        return $this->belongsToMany(ServerGroup::class);
    }

    /** Servers that belong to the given group (by group id). */
    public function scopeInGroup(Builder $query, int $groupId): void
    {
        $query->whereHas('groups', fn (Builder $q) => $q->where('server_groups.id', $groupId));
    }

    /**
     * Servers whose stored SSH credential is present AND not disabled — the live poll set.
     * A disabled ("gesperrt") credential is refused by CredentialVault::resolve() at connect
     * time, but the poller reuses a long-lived connection, so revocation only takes effect if
     * the server also drops OUT of this query on the next tick.
     */
    public function scopeWithActiveCredential(Builder $query): void
    {
        $query->whereHas('credential', fn (Builder $q) => $q->whereNull('disabled_at'));
    }
}
