package com.datamate.common.auth.infrastructure.context;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 从网关透传请求头中提取用户上下文
 */
@Component
public class RequestUserContextInterceptor implements HandlerInterceptor {
    private static final String HEADER_USER_ID = "X-User-Id";
    private static final String HEADER_USER_NAME = "X-User-Name";
    private static final String HEADER_USER_ROLES = "X-User-Roles";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = normalizeValue(request.getHeader(HEADER_USER_ID));
        String username = normalizeValue(request.getHeader(HEADER_USER_NAME));
        List<String> roleCodes = parseRoleCodes(request.getHeader(HEADER_USER_ROLES));
        RequestUserContextHolder.set(RequestUserContext.of(userId, username, roleCodes));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        RequestUserContextHolder.clear();
    }

    private String normalizeValue(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return value.trim();
    }

    private List<String> parseRoleCodes(String roleHeader) {
        if (!StringUtils.hasText(roleHeader)) {
            return Collections.emptyList();
        }
        return Arrays.stream(roleHeader.split(","))
            .map(String::trim)
            .filter(StringUtils::hasText)
            .toList();
    }
}

