<?php
declare(strict_types=1);

namespace App;

/** Fixed-window rate limiter stored in the database. */
final class RateLimit
{
    /** Returns true if this hit is allowed, false once $max hits happened inside $windowSeconds. */
    public static function hit(string $key, int $max, int $windowSeconds): bool
    {
        $key = substr($key, 0, 190);
        $now = now();
        return Db::tx(function () use ($key, $max, $windowSeconds, $now): bool {
            $row = Db::one('SELECT window_start, hits FROM rate_limits WHERE rl_key = ?' . Db::lock(), [$key]);
            if ($row === null) {
                Db::run('INSERT INTO rate_limits (rl_key, window_start, hits) VALUES (?, ?, 1)', [$key, $now]);
                return true;
            }
            if ($now - (int) $row['window_start'] >= $windowSeconds) {
                Db::run('UPDATE rate_limits SET window_start = ?, hits = 1 WHERE rl_key = ?', [$now, $key]);
                return true;
            }
            if ((int) $row['hits'] >= $max) {
                return false;
            }
            Db::run('UPDATE rate_limits SET hits = hits + 1 WHERE rl_key = ?', [$key]);
            return true;
        });
    }

    /** Delete old windows. Run from cron (bin/cron.php). */
    public static function prune(): void
    {
        Db::run('DELETE FROM rate_limits WHERE window_start < ?', [now() - 86400]);
    }
}
