<?php

namespace App\Models;

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

class CaptchaRateLimit extends Model
{
    use HasFactory;

    protected $fillable = [
        'ip_address',
        'location',
        'attempts',
        'failed_attempts',
        'first_attempt_at',
        'last_attempt_at',
        'blocked_until',
    ];

    protected $casts = [
        'attempts' => 'integer',
        'failed_attempts' => 'integer',
        'first_attempt_at' => 'datetime',
        'last_attempt_at' => 'datetime',
        'blocked_until' => 'datetime',
    ];

    /**
     * Check if this rate limit is currently blocked
     */
    public function isBlocked(): bool
    {
        return $this->blocked_until && $this->blocked_until->isFuture();
    }

    /**
     * Get remaining block time in minutes
     */
    public function getRemainingBlockTime(): ?int
    {
        if (!$this->isBlocked()) {
            return null;
        }

        return (int) now()->diffInMinutes($this->blocked_until, false);
    }

    /**
     * Reset rate limit
     */
    public function reset(): void
    {
        $this->update([
            'attempts' => 0,
            'failed_attempts' => 0,
            'blocked_until' => null,
        ]);
    }

    /**
     * Clean old rate limits (older than decay window)
     */
    public static function cleanOldRecords(int $minutes = 60): int
    {
        return self::where('last_attempt_at', '<', now()->subMinutes($minutes))
            ->whereNull('blocked_until')
            ->delete();
    }

    /**
     * Get blocked IPs count
     */
    public static function getBlockedCount(): int
    {
        return self::whereNotNull('blocked_until')
            ->where('blocked_until', '>', now())
            ->count();
    }
}
