<?php

namespace App\Modules\Pilkades\Http\Middleware;

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

/**
 * Dedicated rate limiter for the public voter search endpoint (FR-035):
 * max 10 requests per minute per IP, independent of the general API throttle,
 * so voter-data scraping attempts are constrained even if other endpoints
 * allow more headroom.
 */
class ThrottleVoterSearch
{
    public function __construct(protected RateLimiter $limiter) {}

    public function handle(Request $request, Closure $next): Response
    {
        $key = 'voter-search:'.sha1($request->ip());

        if ($this->limiter->tooManyAttempts($key, 10)) {
            return response()->json([
                'message' => 'Terlalu banyak percobaan pencarian. Silakan coba lagi dalam beberapa saat.',
            ], 429);
        }

        $this->limiter->hit($key, 60);

        return $next($request);
    }
}
