--[[
    配额令牌桶回滚操作脚本
    
    功能说明:
    - 支持令牌的扣减和添加操作
    - 用于配额的动态调整和回滚
    - 提供边界保护(不低于0,不高于容量)
    
    参数说明:
    - KEYS[1]: 令牌桶key
    - ARGV[1]: op - 操作类型 (1: 扣减令牌, 2: 添加令牌)
    - ARGV[2]: tokens - 操作的令牌数量
    - ARGV[3]: capacity - 令牌桶容量
    
    返回值:
    - 成功: {new_tokens, "success message"}
    - 失败: {-1, "error message"}
]]

redis.replicate_commands()

-- 操作类型常量
local OP_DECREMENT = 1
local OP_INCREMENT = 2

-- 获取输入参数
local key = KEYS[1]
local op = tonumber(ARGV[1])
local tokens = tonumber(ARGV[2])
local capacity = tonumber(ARGV[3])

-- Hash字段常量
local TOKENS_FIELD = "tokens"

-- 检查key是否存在
local exists = redis.call('EXISTS', key)
if exists == 0 then
    return {-1, 'key not found'}
end

-- 参数校验
if not tokens or tokens < 0 then
    return {-1, 'invalid tokens value'}
end

if op == OP_DECREMENT then
    -- 扣减令牌: 不低于0
    local current_tokens = tonumber(redis.call('HGET', key, TOKENS_FIELD)) or 0
    local new_tokens = math.max(0, current_tokens - tokens)
    redis.call('HSET', key, TOKENS_FIELD, new_tokens)
    return {new_tokens, 'dec success'}
    
elseif op == OP_INCREMENT then
    -- 添加令牌: 不高于容量
    local current_tokens = tonumber(redis.call('HGET', key, TOKENS_FIELD)) or 0
    local new_tokens = math.min(capacity, current_tokens + tokens)
    redis.call('HSET', key, TOKENS_FIELD, new_tokens)
    return {new_tokens, 'inc success'}
    
else
    return {-1, 'unknown op'}
end