<?php

namespace KeyLair;

use PDO;

/**
 * Fixed-window rate limiting per (ip hash, endpoint). Simple and sufficient
 * to blunt bots / brute-force attempts against claim links without adding
 * an external dependency like Redis.
 */
class RateLimiter
{
    public static function tooManyRequests(
        string $endpoint,
        int $maxRequests = 20,
        int $windowSeconds = 60
    ): bool {
        $pdo = Database::connection();
        $ipHash = Helpers::hashIp(Helpers::clientIp());
        $windowStart = intdiv(time(), $windowSeconds) * $windowSeconds;

        $stmt = $pdo->prepare(
            'INSERT INTO rate_limits (ip_hash, endpoint, window_start, request_count)
             VALUES (:ip, :endpoint, :window, 1)
             ON DUPLICATE KEY UPDATE request_count = request_count + 1'
        );
        $stmt->execute([
            'ip' => $ipHash,
            'endpoint' => $endpoint,
            'window' => $windowStart,
        ]);

        $check = $pdo->prepare(
            'SELECT request_count FROM rate_limits WHERE ip_hash = :ip AND endpoint = :endpoint AND window_start = :window'
        );
        $check->execute([
            'ip' => $ipHash,
            'endpoint' => $endpoint,
            'window' => $windowStart,
        ]);
        $count = (int) $check->fetchColumn();

        // Best-effort cleanup of old windows so the table doesn't grow forever.
        if (random_int(1, 50) === 1) {
            $cleanup = $pdo->prepare('DELETE FROM rate_limits WHERE window_start < :cutoff');
            $cleanup->execute(['cutoff' => time() - (10 * $windowSeconds)]);
        }

        return $count > $maxRequests;
    }
}
