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

import org.springframework.core.NamedThreadLocal;
import org.springframework.util.StringUtils;

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

/**
 * 请求级用户上下文持有器
 */
public final class RequestUserContextHolder {
    private static final ThreadLocal<RequestUserContext> USER_CONTEXT_HOLDER =
        new NamedThreadLocal<>("datamate-request-user-context");

    private RequestUserContextHolder() {
    }

    public static void set(RequestUserContext context) {
        USER_CONTEXT_HOLDER.set(context == null ? RequestUserContext.empty() : context);
    }

    public static RequestUserContext get() {
        RequestUserContext context = USER_CONTEXT_HOLDER.get();
        return context == null ? RequestUserContext.empty() : context;
    }

    public static String getCurrentUserId() {
        return get().getUserId();
    }

    public static List<String> getCurrentRoles() {
        List<String> roles = get().getRoles();
        return roles == null ? Collections.emptyList() : roles;
    }

    public static boolean hasRole(String roleCode) {
        if (!StringUtils.hasText(roleCode)) {
            return false;
        }
        return getCurrentRoles().stream()
            .anyMatch(role -> StringUtils.hasText(role) && roleCode.equalsIgnoreCase(role.trim()));
    }

    public static void clear() {
        USER_CONTEXT_HOLDER.remove();
    }
}

