-- SPDX-License-Identifier: MIT
-- Modified from https://github.com/rwz/redis-gcra/blob/master/vendor/perform_gcra_ratelimit.lua
redis.replicate_commands()

local key = KEYS[1]
local capacity = ARGV[1]
local emission_interval = ARGV[2] * 1000 -- ms to us
local window = capacity * emission_interval

local now = redis.call("TIME")
local sep_1_2025 = 1756684800 -- relative epoch to reduce int size; works for ~31.7 years
now = (now[1] - sep_1_2025) * 1000 * 1000 + now[2]
local tat = tonumber(redis.call("GET", key)) or now
local new_tat = math.max(tat, now) + emission_interval
local diff = now + window - new_tat

if diff < 0 then
  return {0, math.ceil(-diff / 1000 / 1000)}
end

redis.call("SET", key, new_tat, "PX", math.ceil((new_tat - now) / 1000))
return {1, 0}
