package com.cico.nest.lcdp.boot.core.system.context;

import cn.hutool.core.util.StrUtil;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.user.AdminUserDO;
import com.cico.nest.lcdp.boot.core.system.service.user.AdminUserService;
import com.cico.nest.lcdp.boot.security.config.SecurityProperties;
import com.cico.nest.lcdp.boot.security.core.util.SecurityFrameworkUtils;
import com.cico.nest.lcdp.boot.web.holder.LcdpGlobalContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author zws
 * @date 2024/7/26
 */
public class LcdpGlobalContextFilter extends OncePerRequestFilter {

    public LcdpGlobalContextFilter(SecurityProperties securityProperties, AdminUserService adminUserService) {
        this.securityProperties = securityProperties;
        this.adminUserService = adminUserService;
    }

    private final SecurityProperties securityProperties;

    private  final AdminUserService adminUserService;

/*    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return !StrUtil.startWith(request.getRequestURI(),"/actuator");
    }*/

    @Override
    @SuppressWarnings("NullableProblems")
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try{
            LcdpGlobalContextHolder.init(request, LocalDateTime.now());
            String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
            LcdpGlobalContextHolder.setReqToken(token);
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            if(Objects.nonNull(userId)){
                LcdpGlobalContextHolder.setLoginUserId(String.valueOf(userId));
                AdminUserDO adminUser = adminUserService.getUser(userId);
                LcdpGlobalContextHolder.setLoginUser(AdminUserDO.toLoginUserDTO(adminUser));
            }
            // 继续过滤链
            filterChain.doFilter(request, response);
        }finally {
            LcdpGlobalContextHolder.remove();
        }
    }
}
