<?php
namespace App;

use PDO;

final class RateLimiter
{
    /** @var int */
    private $limit;
    /** @var int */
    private $burst;

    public function __construct($perMinute = 60, $burst = 120)
    {
        $this->limit = (int)$perMinute;
        $this->burst = (int)$burst;
    }

    /**
     * true = اجازه بده، false = رد کن
     * جدول لازم: rate_limits(bucket VARCHAR(64), ts_minute INT, count INT, PRIMARY KEY(bucket, ts_minute))
     */
    public function allow($bucket)
    {
        $bucket = (string)$bucket;
        $minute = (int)floor(time() / 60);

        return DB::tx(function (PDO $pdo) use ($bucket, $minute) {
            // افزایش شمارنده تا سقف burst
            $stmt = $pdo->prepare(
                "INSERT INTO rate_limits (bucket, ts_minute, count) VALUES (?, ?, 1)
                 ON DUPLICATE KEY UPDATE count = LEAST(count + 1, ?)"
            );
            $stmt->execute([$bucket, $minute, $this->burst]);

            $check = $pdo->prepare("SELECT count FROM rate_limits WHERE bucket=? AND ts_minute=?");
            $check->execute([$bucket, $minute]);
            $cnt = (int)$check->fetchColumn();

            // اگر از limit عبور کرد، اجازه نده
            return $cnt <= $this->limit;
        });
    }
}
