package tech.easyflow.agent.security;

import com.mybatisflex.core.query.QueryWrapper;
import org.junit.Test;
import org.mockito.MockedStatic;
import tech.easyflow.agent.entity.Agent;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.system.entity.vo.RoleCategoryAccessSnapshot;
import tech.easyflow.system.enums.CategoryResourceType;
import tech.easyflow.system.service.CategoryPermissionService;
import tech.easyflow.system.service.SysDeptService;

import java.math.BigInteger;
import java.util.Locale;
import java.util.Set;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;

/**
 * {@link AgentVisibilityQueryHelper} 未分类 Agent 查询权限回归测试。
 */
public class AgentVisibilityQueryHelperTest {

    /**
     * 验证受限分类角色的读取查询仍包含未分类公开 Agent。
     */
    @Test
    public void restrictedCategoryQueryShouldIncludeUnclassifiedAgents() {
        CategoryPermissionService categoryPermissionService = mock(CategoryPermissionService.class);
        SysDeptService sysDeptService = mock(SysDeptService.class);
        AgentVisibilityQueryHelper helper = new AgentVisibilityQueryHelper(
                categoryPermissionService, sysDeptService);
        LoginAccount account = account(7, 42);
        when(categoryPermissionService.getCurrentAccess(CategoryResourceType.AGENT.getCode()))
                .thenReturn(new RoleCategoryAccessSnapshot(
                        CategoryResourceType.AGENT.getCode(), account.getId(), false, false,
                        Set.of(BigInteger.valueOf(99))));
        QueryWrapper query = QueryWrapper.create().from(Agent.class);

        try (MockedStatic<SaTokenUtil> saToken = mockStatic(SaTokenUtil.class)) {
            saToken.when(SaTokenUtil::getLoginAccount).thenReturn(account);
            helper.applyReadableAccess(query);
        }

        String sql = query.toSQL().toLowerCase(Locale.ROOT);
        assertTrue("受限分类查询缺少未分类 Agent 分支: " + sql,
                sql.contains("category_id") && sql.contains("is null"));
        assertTrue("受限分类查询缺少已授权分类分支: " + sql, sql.contains("category_id` = 99"));
        assertTrue("未分类 Agent 分支未附加可见范围: " + sql,
                sql.matches("(?s).*category_id` is null\\s+and\\s+`visibility_scope` = 'public'.*"));
    }

    /**
     * 创建测试使用的登录账号。
     *
     * @param accountId 账号 ID
     * @param tenantId 租户 ID
     * @return 登录账号
     */
    private LoginAccount account(long accountId, long tenantId) {
        LoginAccount account = new LoginAccount();
        account.setId(BigInteger.valueOf(accountId));
        account.setTenantId(BigInteger.valueOf(tenantId));
        return account;
    }
}
