<?php

namespace App\Models;

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

class AdminIpRestriction extends Model
{
    use HasFactory;

    protected $table = 'admin_ip_restrictions';

    protected $fillable = [
        'user_id',
        'ip_address',
        'type',
        'description',
        'is_active',
        'expires_at',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'expires_at' => 'datetime',
    ];

    /**
     * User relationship
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Check if restriction is currently active
     */
    public function isCurrentlyActive(): bool
    {
        if (!$this->is_active) {
            return false;
        }

        if ($this->expires_at && $this->expires_at->isPast()) {
            $this->update(['is_active' => false]);
            return false;
        }

        return true;
    }

    /**
     * Scope for active restrictions
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('expires_at')
                  ->orWhere('expires_at', '>', now());
            });
    }

    /**
     * Scope for whitelist entries
     */
    public function scopeWhitelist($query)
    {
        return $query->where('type', 'whitelist');
    }

    /**
     * Scope for blacklist entries
     */
    public function scopeBlacklist($query)
    {
        return $query->where('type', 'blacklist');
    }

    /**
     * Scope for specific user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Check if IP is allowed for a user
     */
    public static function isIpAllowed($userId, $ipAddress): bool
    {
        // Check blacklist first
        $blacklisted = self::where('user_id', $userId)
            ->blacklist()
            ->active()
            ->where('ip_address', $ipAddress)
            ->exists();

        if ($blacklisted) {
            return false;
        }

        // If whitelist exists for user, IP must be in whitelist
        $hasWhitelist = self::where('user_id', $userId)
            ->whitelist()
            ->active()
            ->exists();

        if ($hasWhitelist) {
            return self::where('user_id', $userId)
                ->whitelist()
                ->active()
                ->where('ip_address', $ipAddress)
                ->exists();
        }

        // No restrictions
        return true;
    }

    /**
     * Get all active restrictions for user
     */
    public static function getActiveRestrictions($userId)
    {
        return self::where('user_id', $userId)
            ->active()
            ->get()
            ->groupBy('type');
    }
}

