package com.datamate.common.auth.application;

import com.datamate.common.auth.infrastructure.context.RequestUserContextHolder;
import com.datamate.common.infrastructure.exception.BusinessAssert;
import com.datamate.common.infrastructure.exception.SystemErrorCode;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 资源访问控制服务（基于请求用户上下文）
 */
@Service
public class ResourceAccessService {
    public static final String ADMIN_ROLE_CODE = "ROLE_ADMIN";

    public boolean isAdmin() {
        return RequestUserContextHolder.hasRole(ADMIN_ROLE_CODE);
    }

    public String getCurrentUserId() {
        return RequestUserContextHolder.getCurrentUserId();
    }

    public String requireCurrentUserId() {
        String currentUserId = getCurrentUserId();
        BusinessAssert.isTrue(StringUtils.hasText(currentUserId), SystemErrorCode.INSUFFICIENT_PERMISSIONS);
        return currentUserId;
    }

    /**
     * 资源列表查询的 owner 过滤：
     * - 管理员返回 null（不过滤）
     * - 非管理员返回当前用户ID
     */
    public String resolveOwnerFilterUserId() {
        if (isAdmin()) {
            return null;
        }
        return requireCurrentUserId();
    }

    /**
     * 校验当前用户是否可访问 owner 资源
     */
    public void assertOwnerAccess(String ownerUserId) {
        if (isAdmin()) {
            return;
        }
        String currentUserId = requireCurrentUserId();
        BusinessAssert.isTrue(
            StringUtils.hasText(ownerUserId) && Objects.equals(ownerUserId, currentUserId),
            SystemErrorCode.INSUFFICIENT_PERMISSIONS
        );
    }
}

