<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class CheckIpAddress
{
    public function handle(Request $request, Closure $next): Response
    {
        $ip = $request->ip();

        // Check if IP is blacklisted
        if ($this->isIpBlacklisted($ip)) {
            abort(403, 'دسترسی به این آدرس IP مسدود شده است.');
        }

        // Track failed attempts
        if ($this->hasTooManyFailedAttempts($ip)) {
            $this->blacklistIp($ip);
            abort(403, 'به دلیل تلاش‌های ناموفق زیاد، دسترسی به این آدرس IP مسدود شده است.');
        }

        return $next($request);
    }

    protected function isIpBlacklisted(string $ip): bool
    {
        return Cache::get('blacklisted_ip_'.$ip, false);
    }

    protected function hasTooManyFailedAttempts(string $ip): bool
    {
        $attempts = Cache::get('failed_attempts_'.$ip, 0);

        return $attempts >= config('auth.max_failed_attempts', 10);
    }

    protected function blacklistIp(string $ip): void
    {
        Cache::put('blacklisted_ip_'.$ip, true, now()->addHours(24));
    }

    public static function incrementFailedAttempts(string $ip): void
    {
        $key = 'failed_attempts_'.$ip;
        $attempts = Cache::get($key, 0);
        Cache::put($key, $attempts + 1, now()->addMinutes(30));
    }
}
