package cn.reghao.tnb.user.app.config.web;

import cn.reghao.tnb.common.web.ServletUtil;
import cn.reghao.tnb.common.auth.LoginUser;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.common.util.ConstantId;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import jakarta.servlet.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author reghao
 * @date 2023-08-25 21:14:23
 */
@Component
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String requestId = ServletUtil.getHeader("x-request-id");
        MDC.put("request_id", requestId);

        long userId = ConstantId.ANONYMOUS_USER_ID;
        String userIdStr = ServletUtil.getHeader("x-user-id");
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
        }

        String loginId = ConstantId.ANONYMOUS_USER_ID + "";
        String loginIdStr = ServletUtil.getHeader("x-login-id");
        if (loginIdStr != null) {
            loginId = loginIdStr;
        }

        Set<String> roles = new HashSet<>();
        String rolesStr = ServletUtil.getHeader("x-user-roles");
        if (rolesStr != null) {
            roles.addAll(Arrays.asList(rolesStr.split(",")));
        }

        LoginUser loginUser = new LoginUser(userId, loginId, roles);
        try (UserContext context = new UserContext(loginUser)) {
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {
    }
}
