<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class NameServer extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'hostname',
        'ip_address',
        'ipv6_address',
        'api_url',
        'api_key',
        'cloudflare_account_id',
        'api_type',
        'api_port',
        'web_port', // Port pentru web server (query-logs.php)
        'stats_method', // Metoda de colectare statistici: api, ssh, http, none
        'ssh_port',
        'ssh_user',
        'ssh_key_path',
        'log_path',
        'server_id',
        'country_code',
        'city',
        'region',
        'latitude',
        'longitude',
        'provider',
        'datacenter',
        'is_active',
        'is_primary',
        'priority',
        'weight',
        'last_check_at',
        'status',
        'response_time_ms',
        'max_zones',
        'current_zones',
        'description',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'is_primary' => 'boolean',
            'priority' => 'integer',
            'weight' => 'integer',
            'last_check_at' => 'datetime',
            'latitude' => 'decimal:7',
            'longitude' => 'decimal:7',
            'response_time_ms' => 'integer',
            'max_zones' => 'integer',
            'current_zones' => 'integer',
        ];
    }

    /**
     * Relația cu zonele DNS
     */
    public function dnsZones()
    {
        return $this->hasMany(DnsZone::class);
    }

    /**
     * Relația cu statisticile
     */
    public function stats()
    {
        return $this->hasMany(NameServerStat::class);
    }

    /**
     * Scope pentru servere active
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope pentru servere primare
     */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    /**
     * Scope pentru servere online
     */
    public function scopeOnline($query)
    {
        return $query->where('status', 'online');
    }

    /**
     * Scope pentru filtrare după regiune
     */
    public function scopeByRegion($query, $region)
    {
        return $query->where('region', $region);
    }

    /**
     * Scope pentru filtrare după provider
     */
    public function scopeByProvider($query, $provider)
    {
        return $query->where('provider', $provider);
    }

    /**
     * Scope pentru sortare după prioritate
     */
    public function scopeByPriority($query)
    {
        return $query->orderBy('priority', 'asc');
    }

    /**
     * Verifică dacă serverul este activ
     */
    public function isActive(): bool
    {
        return $this->is_active;
    }

    /**
     * Verifică dacă serverul este online
     */
    public function isOnline(): bool
    {
        return $this->status === 'online';
    }

    /**
     * Verifică dacă serverul poate accepta zone noi
     */
    public function canAcceptZones(): bool
    {
        if (!$this->is_active || !$this->isOnline()) {
            return false;
        }

        if ($this->max_zones && $this->current_zones >= $this->max_zones) {
            return false;
        }

        return true;
    }

    /**
     * Obține procentul de utilizare
     */
    public function getUsagePercentageAttribute(): float
    {
        if (!$this->max_zones) {
            return 0;
        }

        return round(($this->current_zones / $this->max_zones) * 100, 2);
    }

    /**
     * Obține badge-ul de status
     */
    public function getStatusBadgeAttribute(): string
    {
        return match($this->status) {
            'online' => 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800',
            'offline' => 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800',
            'degraded' => 'bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-300 border border-yellow-200 dark:border-yellow-800',
            default => 'bg-gray-50 dark:bg-gray-900/50 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700',
        };
    }

    /**
     * Obține iconul de status
     */
    public function getStatusIconAttribute(): string
    {
        return match($this->status) {
            'online' => 'fa-check-circle text-green-500',
            'offline' => 'fa-times-circle text-red-500',
            'degraded' => 'fa-exclamation-triangle text-yellow-500',
            default => 'fa-question-circle text-gray-500',
        };
    }

    /**
     * Obține locația formatată
     */
    public function getLocationAttribute(): string
    {
        $parts = array_filter([
            $this->city,
            $this->country_code,
            $this->region ? "({$this->region})" : null,
        ]);

        return implode(', ', $parts) ?: 'N/A';
    }

    /**
     * Obține URL-ul complet al API-ului
     */
    public function getFullApiUrlAttribute(): string
    {
        if ($this->api_url) {
            return $this->api_url;
        }

        return "http://{$this->ip_address}:{$this->api_port}";
    }
}
