<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CustomRateLimitter
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle($request, Closure $next)
    {

        $ip = $request->ip();
        $timestamp = now()->format('YmdHis'); // e.g., 20250525141230
        $authUserId = auth()->user()->id;
        $url = $request->path(); // Get the URL path (e.g., 'api/users')


        $urlKey = str_replace(['/', '\\'], '_', $url);
        $key = "rate_limit_{$ip}_{$timestamp}_{$authUserId}_{$urlKey}";


        $maxRequestsPerSecond = 1; // Customize this limit

        $requests = Cache::get($key, 0);

        if ($requests >= $maxRequestsPerSecond) {
            return response()->json(['message' => 'Too many requests. Please slow down.'], 429);
        }

        Cache::put($key, $requests + 1, now()->addSeconds(1)); // Set expiry to 1 second

        return $next($request);
    }
}
