package com.writeoff.security;

public class AuthContext {
    private static final ThreadLocal<Long> USER_ID_HOLDER = new ThreadLocal<>();
    private static final ThreadLocal<Long> TENANT_ID_HOLDER = new ThreadLocal<>();
    private static final ThreadLocal<AuthScope> SCOPE_HOLDER = new ThreadLocal<>();

    private AuthContext() {
    }

    public static void set(Long userId, Long tenantId, AuthScope scope) {
        USER_ID_HOLDER.set(userId);
        TENANT_ID_HOLDER.set(tenantId);
        SCOPE_HOLDER.set(scope);
    }

    public static void set(Long userId, Long tenantId) {
        set(userId, tenantId, AuthScope.TENANT);
    }

    public static Long userId() {
        return USER_ID_HOLDER.get();
    }

    public static Long tenantId() {
        return TENANT_ID_HOLDER.get();
    }

    public static Long requireTenantId() {
        Long tenantId = TENANT_ID_HOLDER.get();
        if (tenantId == null) {
            throw new IllegalStateException("tenant context required");
        }
        return tenantId;
    }

    public static AuthScope scope() {
        AuthScope scope = SCOPE_HOLDER.get();
        return scope == null ? AuthScope.TENANT : scope;
    }

    public static void clear() {
        USER_ID_HOLDER.remove();
        TENANT_ID_HOLDER.remove();
        SCOPE_HOLDER.remove();
    }
}
