<?php

declare(strict_types=1);

namespace BotGuard\Services\Detection\Modules;

use BotGuard\Services\Detection\ModuleResult;
use BotGuard\Services\Detection\SignalBag;

/**
 * Rate-limiting / velocity module.
 *
 * Reads per-IP request counts (per second / minute / hour) that the API
 * controller injects into the SignalBag from the durable rate_limits store, and
 * penalises volumes no human could generate. Thresholds are configurable via
 * config('detection_limits.*').
 */
final class RateLimitModule extends AbstractModule
{
    public function key(): string
    {
        return 'rate_limit';
    }

    public function analyze(SignalBag $signals): ModuleResult
    {
        // Velocity counters are injected server-side into the signal bag under
        // "rate.*" by the API controller (from the durable rate_limits store).
        $perSecond = (int) ($signals->client('rate.per_second') ?? 0);
        $perMinute = (int) ($signals->client('rate.per_minute') ?? 0);
        $perHour = (int) ($signals->client('rate.per_hour') ?? 0);

        $maxSecond = (int) config('detection_limits.per_second', 5);
        $maxMinute = (int) config('detection_limits.per_minute', 90);
        $maxHour = (int) config('detection_limits.per_hour', 1200);

        $this->detail('per_second', $perSecond);
        $this->detail('per_minute', $perMinute);
        $this->detail('per_hour', $perHour);

        $this->check("<= {$maxSecond} req/s", $perSecond <= $maxSecond, 3.0);
        $this->check("<= {$maxMinute} req/min", $perMinute <= $maxMinute, 2.0);
        $this->check("<= {$maxHour} req/hour", $perHour <= $maxHour, 1.0);

        // With no velocity data at all, treat as neutral-positive (first visit).
        return $this->result(0.85);
    }
}
