package com.inspect.gateway.filter;

import com.inspect.base.core.constant.TokenConst;
import com.inspect.base.core.utils.JwtUtils;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.redis.service.RedisService;
import com.inspect.gateway.config.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequest.Builder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    private final IgnoreWhiteProperties ignoreWhite;
    private final RedisService redisService;

    public AuthFilter(IgnoreWhiteProperties ignoreWhite, RedisService redisService) {
        this.ignoreWhite = ignoreWhite;
        this.redisService = redisService;
    }

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        final ServerHttpRequest request = exchange.getRequest();
        log.info("requestUrlPath: {}, whites: {}", request.getURI().getPath(), ignoreWhite.getWhites());
        if (StringUtils.matches(request.getURI().getPath(), ignoreWhite.getWhites())) {
            log.info("requestUrlPath: {}, filter ok", request.getURI().getPath());
            return chain.filter(exchange);
        }

        log.info("requestUrlPath: {}, filter next chain", request.getURI().getPath());
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, TokenConst.RESP_TOKEN_NULL);
        }

        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, TokenConst.RESP_TOKEN_EXPIRE);
        }

        String userKey = JwtUtils.getUserKey(claims);
        log.info("[GAB] userKey={}, Uri=[{}]", userKey, request.getURI().getPath());
        boolean isLogin = redisService.hasKey(getTokenKey(userKey));
        if (!isLogin) {
            return unauthorizedResponse(exchange, TokenConst.RESP_REDIS_EXPIRE);
        }

        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            return unauthorizedResponse(exchange, TokenConst.RESP_TOKEN_FAIL);
        }

        Builder mutate = request.mutate();
        addHeader(mutate, TokenConst.USER_KEY, userKey);
        addHeader(mutate, TokenConst.USER_ID, userid);
        addHeader(mutate, TokenConst.USERNAME, username);
        removeHeader(mutate, TokenConst.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());

    }

    private void addHeader(Builder mutate, String name, Object value) {
        if (value != null) {
            String valueStr = value.toString();
            String valueEncode = ServletUtils.urlEncode(valueStr);
            mutate.header(name, valueEncode);
        }
    }

    private void removeHeader(Builder mutate, String name) {
        mutate.headers((httpHeaders) -> {
            httpHeaders.remove(name);
        }).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[GAB] REQUEST URI: {}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, 401);
    }

    private String getTokenKey(String token) {
        return TokenConst.LOGIN_TOKENS + token;
    }

    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConst.AUTHENTICATION);
        if (StringUtils.isBlank(token)) {
            token = request.getQueryParams().getFirst(TokenConst.DOWN_TOKEN);
        }

        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConst.BEARER)) {
            token = token.replaceFirst(TokenConst.BEARER, StringUtils.EMPTY);
        }

        return token;
    }

    public int getOrder() {
        return -200;
    }
}
