package com.yaoai.domain.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yaoai.domain.entity.AiTask;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface AiTaskMapper extends BaseMapper<AiTask> {

    @Select("SELECT * FROM ai_tasks WHERE project_id=#{projectId} AND tenant_id=#{tenantId} ORDER BY created_at DESC")
    List<AiTask> findByProject(Long projectId, Long tenantId);

    @Select("SELECT * FROM ai_tasks WHERE episode_id=#{episodeId} ORDER BY created_at DESC LIMIT 1")
    AiTask findLatestByEpisode(Long episodeId);

    @Select("""
            SELECT t.* FROM ai_tasks t
            LEFT JOIN storyboards s ON t.storyboard_id = s.id
            WHERE t.episode_id = #{episodeId}
              AND t.tenant_id  = #{tenantId}
              AND t.status = 'succeeded'
              AND t.result_video_url IS NOT NULL
            ORDER BY COALESCE(s.sequence_num, 9999), t.created_at
            """)
    List<AiTask> findSucceededByEpisodeOrdered(Long episodeId, Long tenantId);

    /** 待轮询的视频任务：已提交 Ark 且未到终态。limit 控制单轮处理上限，避免单次扫描挤占线程。 */
    @Select("""
            SELECT * FROM ai_tasks
            WHERE (
                status IN ('submitted','running')
                OR (status = 'succeeded' AND (result_video_url IS NULL OR result_video_url = ''))
              )
              AND external_task_id IS NOT NULL
            ORDER BY created_at ASC
            LIMIT #{limit}
            """)
    List<AiTask> findPollableVideoTasks(int limit);

    @Select("""
            SELECT * FROM ai_tasks
            WHERE storyboard_id = #{storyboardId}
              AND tenant_id = #{tenantId}
              AND status = 'succeeded'
              AND result_video_url IS NOT NULL
              AND result_video_url <> ''
            ORDER BY created_at DESC
            LIMIT 1
            """)
    AiTask findLatestSucceededVideoByStoryboard(Long storyboardId, Long tenantId);
}
