package tech.easyflow.agent.mapper;

import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import tech.easyflow.agent.entity.AgentArtifact;

import java.util.List;

/**
 * Agent Artifact 状态账本 Mapper。
 */
public interface AgentArtifactMapper extends BaseMapper<AgentArtifact> {

    /**
     * 有界查询正式会话已删除、缺失或归属不一致的 Artifact。
     *
     * @param limit 最大返回数量
     * @return 待补偿删除的 Artifact
     */
    @Select("""
            SELECT artifact.*
            FROM tb_agent_artifact artifact
            WHERE artifact.is_deleted = 0
              AND artifact.chat_mode = 'FORMAL'
              AND artifact.status IN ('PUBLISHING', 'AVAILABLE', 'FAILED', 'DELETE_FAILED')
              AND NOT EXISTS (
                    SELECT 1
                    FROM chat_session chat
                    WHERE chat.id = artifact.chat_session_id
                      AND chat.is_deleted = 0
                      AND chat.assistant_code = 'AGENT'
                      AND chat.tenant_id = artifact.tenant_id
                      AND chat.user_id = artifact.owner_user_id
                      AND chat.assistant_id = artifact.agent_id
              )
            ORDER BY artifact.id
            LIMIT #{limit}
            """)
    List<AgentArtifact> selectOrphanedFormalArtifacts(@Param("limit") int limit);
}
