<?php

namespace App\Http\Middleware;

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

class RateLimitPerUser
{
    public function __construct(private RateLimiter $limiter)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        // TODO: Determine user identity source; fallback to IP for scaffold
        $key = 'ai:rate:' . ($request->user()->id ?? $request->ip());
        $max = 5; // per minute
        if ($this->limiter->tooManyAttempts($key, $max)) {
            $retry = $this->limiter->availableIn($key);
            return response('Too Many Requests', 429)->header('Retry-After', (string) $retry);
        }
        $this->limiter->hit($key, 60);
        return $next($request);
    }
}

