package com.ruoyi.gateway.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.ruoyi.common.core.exception.BusinessException;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.utils.FebsUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.gateway.enhance.entity.RateLimitRule;
import com.ruoyi.gateway.enhance.service.RouteEnhanceCacheService;
import com.ruoyi.gateway.enhance.service.RouteEnhanceService;
import com.ruoyi.gateway.service.ValidateCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.net.URI;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 验证码获取
 *
 * <p>v1:限流</p>
 * @author ruoyi
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ValidateCodeHandler implements HandlerFunction<ServerResponse>
{
    private final ValidateCodeService validateCodeService;

    @Value("${febs.gateway.enhance:false}")
    private Boolean routeEhance;

    private final RouteEnhanceCacheService routeEnhanceCacheService;

    private final RouteEnhanceService routeEnhanceService;

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest)
    {
        AjaxResult ajax;
        try
        {
            if (routeEhance) {
                ServerWebExchange exchange = serverRequest.exchange();
                Stopwatch stopwatch = Stopwatch.createStarted();
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();
                String requestIp = FebsUtil.getServerHttpRequestIpAddress(request);
                String requestMethod = request.getMethodValue();
                AtomicBoolean limit = new AtomicBoolean(false);
                String path = "/code";

                Set<Object> blackList = routeEnhanceCacheService.getBlackList(requestIp);
                blackList.addAll(routeEnhanceCacheService.getBlackList());
                routeEnhanceService.doBlackListCheck(limit, blackList, URI.create(path), requestMethod);
                log.info("Blacklist verification completed - {}", stopwatch.stop());
                if (limit.get()) {
                    return Mono.error(new BusinessException("黑名单限制，禁止访问"));
                }

                Stopwatch stopwatchRule = Stopwatch.createStarted();
                Object o = routeEnhanceCacheService.getRateLimitRule(path, requestMethod);
                if (o != null) {
                    RateLimitRule rule = JSONObject.parseObject(o.toString(), RateLimitRule.class);
                    Mono<Void> result = routeEnhanceService.doRateLimitCheck(limit, rule, URI.create(path), requestIp, requestMethod, response);
                    log.info("Rate limit verification completed - {}", stopwatchRule.stop());
                    if (result != null) {
                        return Mono.error(new BusinessException("请求过于频繁，请稍后再试"));
                    }
                }
            }
            ajax = validateCodeService.createCaptcha();
        }
        catch (CaptchaException | IOException e)
        {
            return Mono.error(e);
        }
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
    }
}
