<?php

namespace App\Models;

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

class NameserverStatusHistory extends Model
{
    use HasFactory;

    protected $table = 'nameserver_status_history';

    protected $fillable = [
        'nameserver_id',
        'old_status',
        'new_status',
        'reason',
        'response_time_ms',
        'checked_at',
    ];

    protected $casts = [
        'checked_at' => 'datetime',
    ];

    /**
     * Relație cu nameserver-ul
     */
    public function nameserver()
    {
        return $this->belongsTo(NameServer::class, 'nameserver_id');
    }

    /**
     * Verifică dacă a fost o tranziție de la offline la online
     */
    public function wasRecovery(): bool
    {
        return $this->old_status === 'offline' && $this->new_status === 'online';
    }

    /**
     * Verifică dacă a fost o cădere
     */
    public function wasOutage(): bool
    {
        return $this->old_status === 'online' && $this->new_status === 'offline';
    }

    /**
     * Log o schimbare de status
     */
    public static function logStatusChange(
        int $nameserverId,
        ?string $oldStatus,
        string $newStatus,
        ?string $reason = null,
        ?int $responseTimeMs = null
    ): self {
        return self::create([
            'nameserver_id' => $nameserverId,
            'old_status' => $oldStatus,
            'new_status' => $newStatus,
            'reason' => $reason,
            'response_time_ms' => $responseTimeMs,
            'checked_at' => now(),
        ]);
    }

    /**
     * Curăță istoricul vechi
     */
    public static function cleanup(int $daysOld = 30): int
    {
        return self::where('checked_at', '<', now()->subDays($daysOld))->delete();
    }
}
