package tech.easyflow.agent.runtime.hitl;

import org.junit.Test;
import org.mockito.Mockito;
import tech.easyflow.agent.entity.AgentHitlPending;
import tech.easyflow.agent.runtime.AgentRunService;

import java.util.List;

/**
 * {@link AgentHitlPendingExpirationTask} 回归测试。
 */
public class AgentHitlPendingExpirationTaskTest {

    /**
     * 验证数据库审批过期后通知所有运行节点，单条通知失败不阻断同批其他记录。
     */
    @Test
    public void expirePendingShouldNotifyEveryRuntime() {
        AgentHitlPendingService pendingService = Mockito.mock(AgentHitlPendingService.class);
        AgentRunService runService = Mockito.mock(AgentRunService.class);
        AgentHitlPending first = pending("request-1", "token-1");
        AgentHitlPending second = pending("request-2", "token-2");
        Mockito.when(pendingService.expirePending(100)).thenReturn(List.of(first, second));
        Mockito.doThrow(new RuntimeException("owner unavailable"))
                .when(runService).expireApproval("request-1", "token-1");
        AgentHitlPendingExpirationTask task =
                new AgentHitlPendingExpirationTask(pendingService, runService);

        task.expirePending();

        Mockito.verify(runService).expireApproval("request-1", "token-1");
        Mockito.verify(runService).expireApproval("request-2", "token-2");
    }

    /**
     * 创建已过期审批记录。
     *
     * @param requestId 请求 ID
     * @param resumeToken 恢复令牌
     * @return 审批记录
     */
    private AgentHitlPending pending(String requestId, String resumeToken) {
        AgentHitlPending pending = new AgentHitlPending();
        pending.setRequestId(requestId);
        pending.setResumeToken(resumeToken);
        pending.setStatus(AgentHitlPendingStatus.EXPIRED.name());
        return pending;
    }
}
