package com.sonic.common.ratelimit;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

public interface RateLimiterClient {

    /**
     * 构建一个基于Redis的RateLimiter
     *
     * @return
     */
    RateLimiter build(RateLimiterReq rateLimiterReq);

    /**
     * 根据windowType与ruleExpression构建一个基于Redis的RateLimiter
     * express eg: 10/1,20/1... 代表10秒1次 & 20秒1次...
     *
     * @param limiterKey
     * @param windowType
     * @param ruleExpression 规则表达式
     * @return
     */
    default RateLimiter build(String limiterKey, RateLimiter.WindowType windowType, String ruleExpression) {
        return build(RateLimiterReq.builder()
                .windowType(windowType)
                .rules(RateLimiter.LimitRule.fromExpression(ruleExpression))
                .limiterKey(limiterKey)
                .build());
    }

    @Data
    @Builder
    @AllArgsConstructor
    class RateLimiterReq {
        RateLimiter.WindowType windowType;
        List<RateLimiter.LimitRule> rules;
        String limiterKey;
    }
}
