<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;
use App\Http\Helpers\CloudflareHelper;
use Carbon\Carbon;

class DetectAttack
{
    public function handle($request, Closure $next)
{
    $key = 'request_count_' . now()->format('YmdHi');
    $count = Cache::increment($key, 1);
    Cache::put($key, $count, now()->addMinutes(2));

    if ($count > 1000 && !Cache::has('cloudflare_under_attack')) {
        CloudflareHelper::setIUAM('under_attack');
        Cache::put('cloudflare_under_attack', true, 3600); // hold for 1 hour
    }

    // If load drops below threshold, switch back (optional reset logic)
    if ($count < 100 && Cache::has('cloudflare_under_attack')) {
        // CloudflareHelper::setIUAM('medium');
        // Cache::forget('cloudflare_under_attack');
    }

    return $next($request);
}

}
