package tech.easyflow.agent.runtime;

import com.mybatisflex.core.query.QueryWrapper;
import org.junit.Test;
import tech.easyflow.agent.entity.Agent;
import tech.easyflow.agent.service.AgentService;
import tech.easyflow.ai.enums.PublishStatus;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.math.BigInteger;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * {@link AgentRunStartGuard} 单元测试。
 */
public class AgentRunStartGuardTest {

    /**
     * 已启用且已发布的 Agent 允许启动正式运行。
     */
    @Test
    public void publishedAgentShouldBeRunnable() {
        AgentService agentService = mock(AgentService.class);
        Agent agent = agent(1, PublishStatus.PUBLISHED);
        when(agentService.getOne(any(QueryWrapper.class))).thenReturn(agent);

        new AgentRunStartGuard(agentService).assertRunnable(BigInteger.valueOf(1001));
    }

    /**
     * 已下线 Agent 必须拒绝新运行。
     */
    @Test(expected = BusinessException.class)
    public void offlineAgentShouldBeRejected() {
        AgentService agentService = mock(AgentService.class);
        when(agentService.getOne(any(QueryWrapper.class)))
                .thenReturn(agent(1, PublishStatus.OFFLINE));

        new AgentRunStartGuard(agentService).assertRunnable(BigInteger.valueOf(1001));
    }

    /**
     * 已禁用 Agent 必须拒绝新运行。
     */
    @Test(expected = BusinessException.class)
    public void disabledAgentShouldBeRejected() {
        AgentService agentService = mock(AgentService.class);
        when(agentService.getOne(any(QueryWrapper.class)))
                .thenReturn(agent(0, PublishStatus.PUBLISHED));

        new AgentRunStartGuard(agentService).assertRunnable(BigInteger.valueOf(1001));
    }

    /**
     * 创建测试 Agent。
     *
     * @param status 启用状态
     * @param publishStatus 发布状态
     * @return 测试 Agent
     */
    private static Agent agent(Integer status, PublishStatus publishStatus) {
        Agent agent = new Agent();
        agent.setId(BigInteger.valueOf(1001));
        agent.setStatus(status);
        agent.setPublishStatus(publishStatus.getCode());
        return agent;
    }
}
