package com.kxs.gateway.api.filter;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kxs.common.core.constant.CacheConstants;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.exception.ValidateCodeException;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.WebUtils;
import com.kxs.gateway.api.config.GatewayConfigProperties;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 验证码网关过滤器
 *
 * @author Lxq
 * @date 2023-11-11
 */
@Slf4j
@RequiredArgsConstructor
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory<Object> {

	private final GatewayConfigProperties configProperties;

	private final ObjectMapper objectMapper;

	private final RedisTemplate<String, Object> redisTemplate;

	/**
	 * 应用网关过滤器
	 * @param config 配置对象
	 * @return 网关过滤器
	 */
	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			boolean isAuthToken = CharSequenceUtil.containsAnyIgnoreCase(request.getURI().getPath(),
					SecurityConstants.OAUTH_TOKEN_URL);

			if (!isAuthToken || isRefreshTokenRequest(request)) {
				return chain.filter(exchange);
			}

			boolean isIgnoreClient = configProperties.getIgnoreClients().contains(WebUtils.getClientId(request));
			try {
				if (!isIgnoreClient) {
					checkCode(request);
				}
			}
			catch (Exception e) {
				ServerHttpResponse response = exchange.getResponse();
				response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
				response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

				final String errMsg = e.getMessage();
				return response.writeWith(Mono.create(monoSink -> {
					try {
						byte[] bytes = objectMapper.writeValueAsBytes(R.failed(errMsg));
						DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

						monoSink.success(dataBuffer);
					}
					catch (JsonProcessingException jsonProcessingException) {
						log.error("对象输出异常", jsonProcessingException);
						monoSink.error(jsonProcessingException);
					}
				}));
			}

			return chain.filter(exchange);
		};
	}

	/**
	 * 判断是否为刷新令牌请求
	 * @param request HTTP请求
	 * @return 是否为刷新令牌请求
	 */
	private boolean isRefreshTokenRequest(ServerHttpRequest request) {
		return CharSequenceUtil.equals(SecurityConstants.REFRESH_TOKEN,
				request.getQueryParams().getFirst("grant_type"));
	}

	/**
	 * 检查验证码
	 * @param request HTTP请求
	 * @throws ValidateCodeException 验证码异常
	 */
	@SneakyThrows
	private void checkCode(ServerHttpRequest request) {
		String code = request.getQueryParams().getFirst("code");

		if (CharSequenceUtil.isBlank(code)) {
			throw new ValidateCodeException(ErrorTypeEnum.VERIFICATION_CODE_IS_EMPTY.getDescription());
		}

		String randomStr = CharSequenceUtil.blankToDefault(request.getQueryParams().getFirst("randomStr"),
				request.getQueryParams().getFirst(SecurityConstants.SMS_PARAMETER_NAME));

		String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;

		Object codeObj = redisTemplate.opsForValue().get(key);

		if (ObjectUtil.isEmpty(codeObj) || !Objects.equals(code, codeObj)) {
			throw new ValidateCodeException(ErrorTypeEnum.VERIFICATION_CODE_IS_ILLEGAL.getDescription());
		}

		redisTemplate.delete(key);
	}

}
