<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BlockedIp extends Model
{
    protected $fillable = ['ip_address', 'level', 'reason', 'blocked_by', 'expires_at'];

    protected function casts(): array
    {
        return ['expires_at' => 'datetime'];
    }

    public function blocker(): BelongsTo
    {
        return $this->belongsTo(AdminUser::class, 'blocked_by');
    }

    public static function isBlocked(string $ip): ?self
    {
        return self::where('ip_address', $ip)
            ->where('level', 'blocked')
            ->where(function ($q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
            })->first();
    }

    public static function isDegraded(string $ip): ?self
    {
        return self::where('ip_address', $ip)
            ->where(function ($q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
            })->first();
    }
}
