package com.microservices.common.security.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.domain.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler  {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException ex) throws Exception {

        R<?> body;
        if (ex instanceof FlowException) {               // 限流
            body = R.fail(429, "请求过于频繁，请稍后重试");
        } else if (ex instanceof DegradeException) {    // 熔断
            body = R.fail(500, "服务暂时不可用，请稍后重试");
        } else if (ex instanceof ParamFlowException) {  // 热点参数限流
            body = R.fail(400, "热点参数限流");
        } else if (ex instanceof AuthorityException) {  // 授权规则
            body = R.fail(403, "无权限访问该资源");
        } else if (ex instanceof SystemBlockException) { // 系统规则
            body = R.fail(500, "系统规则限制，无法访问");
        } else {                                        // 兜底
            body = R.fail(500, "服务繁忙，请稍后重试");
        }

        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONObject.toJSONString(body));
    }
}
