package tech.easyflow.ai.permission;

import cn.dev33.satoken.stp.StpUtil;
import org.junit.Test;
import org.mockito.MockedStatic;
import tech.easyflow.common.web.exceptions.BusinessException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mockStatic;

/**
 * {@link McpAccessPermissionChecker} 的现有 MCP RBAC 语义回归测试。
 */
public class McpAccessPermissionCheckerTest {

    /**
     * 未登录调用方必须收到 401。
     */
    @Test
    public void unauthenticatedCallerIsRejected() {
        try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
            stpUtil.when(StpUtil::isLogin).thenReturn(false);

            BusinessException exception = assertThrows(BusinessException.class,
                    () -> new McpAccessPermissionChecker().assertCanUseMcp());

            assertEquals(401, exception.getHttpStatus());
            assertFalse(new McpAccessPermissionChecker().canUseMcp());
        }
    }

    /**
     * 已登录但缺少 MCP 查询权限的调用方必须收到 403。
     */
    @Test
    public void callerWithoutMcpQueryPermissionIsRejected() {
        try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
            stpUtil.when(StpUtil::isLogin).thenReturn(true);
            stpUtil.when(() -> StpUtil.hasPermission(McpAccessPermissionChecker.MCP_QUERY_PERMISSION))
                    .thenReturn(false);

            BusinessException exception = assertThrows(BusinessException.class,
                    () -> new McpAccessPermissionChecker().assertCanUseMcp());

            assertEquals(403, exception.getHttpStatus());
            assertFalse(new McpAccessPermissionChecker().canUseMcp());
        }
    }

    /**
     * MCP 查询权限同时授予 MCP 候选查看和绑定使用能力。
     */
    @Test
    public void mcpQueryPermissionAllowsUse() {
        try (MockedStatic<StpUtil> stpUtil = mockStatic(StpUtil.class)) {
            stpUtil.when(StpUtil::isLogin).thenReturn(true);
            stpUtil.when(() -> StpUtil.hasPermission(McpAccessPermissionChecker.MCP_QUERY_PERMISSION))
                    .thenReturn(true);
            McpAccessPermissionChecker checker = new McpAccessPermissionChecker();

            checker.assertCanUseMcp();

            assertTrue(checker.canUseMcp());
        }
    }
}
