package com.red.circle.console.infra.framework.security;

import com.red.circle.framework.core.request.RequestAttrConstant;
import com.red.circle.framework.core.request.RequestHeaderConstant;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.framework.dto.IResponseErrorCode;
import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.framework.web.util.JwtUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.text.StringPool;
import com.red.circle.tool.core.text.StringUtils;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

/**
 * 安全认证拦截器.
 * <p>可扩展：  resourceService.listResourcePerms 资源更细力度权限验证等</p>
 *
 * @author pengliang on 2023/10/8 14:28
 */
@Component
@RequiredArgsConstructor
@WebFilter(filterName = "SecurityFilter", urlPatterns = "/*")
@EnableConfigurationProperties(ConsoleSecurityProperties.class)
public class SecurityFilter implements Filter {

  private final PathMatcher pathMatcher = new AntPathMatcher();
  private final ConsoleSecurityProperties consoleSecurityProperties;

  @Override
  public void doFilter(ServletRequest request, ServletResponse res,
      FilterChain chain) throws ServletException, IOException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    if (isIgnoreMatcherPath(httpServletRequest)) {
      chain.doFilter(request, res);
      return;
    }

    String reqToken = getBearerToken(httpServletRequest);

    if (StringUtils.isBlank(reqToken) || JwtUtils.isExpired(reqToken)) {
      responseFailureUnauthorized(res);
      return;
    }

    String reqUserId = (String) request.getAttribute(RequestAttrConstant.REQ_UID);
    Long userId = JwtUtils.getUid(reqToken);
    if (Objects.isNull(userId)) {
      responseFailureUnauthorized(res);
      return;
    }

    // 传递请求用户和token不匹配
    if (StringUtils.isNotBlank(reqUserId)
        && !StringUtils.equalsIgnoreCase(reqUserId, userId.toString())) {
      responseFailureUnauthorized(res);
      return;
    }
    request.setAttribute(RequestAttrConstant.REQ_UID, userId);
    chain.doFilter(request, res);
  }

  private boolean isIgnoreMatcherPath(HttpServletRequest request) {
    for (String ignoreUrl : consoleSecurityProperties.getIgnoreUrls()) {
      if (pathMatcher.match(ignoreUrl, request.getRequestURI())) {
        return true;
      }
    }
    return false;
  }

  private String getBearerToken(HttpServletRequest request) {
    String reqToken = (String) request.getAttribute(RequestAttrConstant.REQ_TOKEN);

    if (StringUtils.isNotBlank(reqToken)) {
      return reqToken;
    }

    String token = request.getHeader(RequestHeaderConstant.AUTHORIZATION);
    return StringUtils.isBlank(token)
        ? StringPool.EMPTY
        : token.replaceFirst("Bearer", "").trim();
  }

  private void responseFailureUnauthorized(ServletResponse response) {
    responseFailure((HttpServletResponse) response, ResponseErrorCode.UNAUTHORIZED);
  }

  /**
   * 响应失败结果.
   */
  @SneakyThrows
  private void responseFailure(HttpServletResponse response,
      IResponseErrorCode errorCode) {
    if (errorCode.getCode() < 600) {
      response.setStatus(errorCode.getCode());
    }
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.getWriter().write(Objects
        .requireNonNull(JacksonUtils.toJson(ResultResponse.failure(errorCode))));
  }

}
