package tech.easyflow.agent.runtime;

import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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;

/**
 * 在正式 Agent 运行注册前通过数据库行锁确认最新生命周期状态。
 */
@Service
public class AgentRunStartGuard {

    private final AgentService agentService;

    /**
     * 创建 Agent 运行启动守卫。
     *
     * @param agentService Agent 服务
     */
    public AgentRunStartGuard(AgentService agentService) {
        this.agentService = agentService;
    }

    /**
     * 锁定 Agent 行并确认当前仍可启动正式运行。
     *
     * @param agentId Agent ID
     * @throws BusinessException Agent 已下线、删除或不可用时抛出
     */
    @Transactional(rollbackFor = Exception.class)
    public void assertRunnable(BigInteger agentId) {
        Agent agent = agentService.getOne(QueryWrapper.create()
                .select(Agent::getId, Agent::getStatus, Agent::getPublishStatus)
                .eq(Agent::getId, agentId)
                .forUpdate());
        if (agent == null
                || !Integer.valueOf(1).equals(agent.getStatus())
                || PublishStatus.from(agent.getPublishStatus()) != PublishStatus.PUBLISHED) {
            throw new BusinessException("当前 Agent 已下线或不可继续会话");
        }
    }
}
