<?php

namespace App\Http\Middleware;

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

class RegistrationRateLimit
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Get IP address (handle proxies and load balancers)
        $ip = $request->header('CF-Connecting-IP') ??
              $request->header('X-Forwarded-For') ??
              $request->ip();
        $ip = trim(explode(',', $ip)[0]);

        // Check for suspicious IP blocking
        $suspiciousKey = 'register:suspicious:' . $ip;
        if (Cache::has($suspiciousKey)) {
            Log::warning('Middleware blocked suspicious IP from registration', ['ip' => $ip]);
            return response()->json([
                'status' => 'error',
                'message' => 'Registration temporarily unavailable. Please contact support.'
            ], 403);
        }

        // Rate limiting configuration
        $rateLimitKey = 'register:' . $ip;
        $maxAttempts = 50; // Maximum 3 registration attempts
        $decayMinutes = 60; // Per 60 minutes (1 hour)

        // Check if rate limit exceeded
        if (RateLimiter::tooManyAttempts($rateLimitKey, $maxAttempts)) {
            $seconds = RateLimiter::availableIn($rateLimitKey);
            $minutes = ceil($seconds / 60);
            
            Log::warning('Middleware: Registration rate limit exceeded', [
                'ip' => $ip,
                'attempts' => RateLimiter::attempts($rateLimitKey),
                'retry_after_minutes' => $minutes
            ]);
            
            return response()->json([
                'status' => 'error',
                'message' => "Too many registration attempts. Please try again in {$minutes} minutes.",
                'retry_after_seconds' => $seconds
            ], 429);
        }

        // Additional check: Block rapid requests (more than 1 request per minute)
        $rapidKey = 'register:rapid:' . $ip;
        if (Cache::has($rapidKey)) {
            // This IP is making requests too quickly - mark as suspicious
            Cache::put($suspiciousKey, true, now()->addHours(24));
            
            Log::warning('Middleware: Rapid registration attempts detected', [
                'ip' => $ip,
                'blocked_for' => '24 hours'
            ]);
            
            return response()->json([
                'status' => 'error',
                'message' => 'Too many rapid requests. Your IP has been temporarily blocked.'
            ], 429);
        }

        // Set rapid request detection (1 minute window)
        Cache::put($rapidKey, true, now()->addMinute());

        return $next($request);
    }
}
