<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class RouteServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->configureRateLimiting();
    }

    protected function configureRateLimiting(): void
    {
        // Login: 5 attempts per minute per email+ip
        RateLimiter::for('auth', function (Request $request) {
            $key = strtolower((string) $request->input('email')) . '|' . $request->ip();
            return Limit::perMinute(5)->by($key)->response(function () {
                return response()->json([
                    'message' => 'Too many login attempts. Try again in a minute.',
                ], 429);
            });
        });

        // Default API: 600 requests per minute per user (or 120 per IP for guests).
        // Generous because the dashboard polls many endpoints in parallel and a
        // single page-load can fire 8-12 requests; users browsing quickly across
        // sections used to hit the previous 60/min cap as a 429 wall.
        RateLimiter::for('api', function (Request $request) {
            $user = $request->user();
            return $user
                ? Limit::perMinute(600)->by('user:' . $user->id)
                : Limit::perMinute(120)->by('ip:' . $request->ip());
        });

        // Agent push: per-server bucket. Default 120/min, configurable via env.
        // Keyed on X-Server-Id so one misbehaving agent can't starve healthy
        // ones (which is what would happen if we keyed on IP — multi-server
        // shared-NAT setups would all share one bucket).
        //
        // Returns 429 with Retry-After so the agent's adaptive interval logic
        // backs off automatically without us building a separate slow-down
        // protocol.
        RateLimiter::for('agent-push', function (Request $request) {
            $perMinute = (int) config('monitoring.agent_push_rate_limit_per_minute', 120);
            $key = $request->header('X-Server-Id') ?: $request->ip();
            return Limit::perMinute($perMinute)->by("agent:{$key}")
                ->response(function () {
                    return response()->json([
                        'error' => 'rate_limited',
                        'message' => 'Push rate exceeded. Reduce push frequency or contact NOC operator.',
                    ], 429);
                });
        });
    }
}
