package com.example.demo.repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.demo.model.StoryboardVideoTask;

@Repository
public interface StoryboardVideoTaskRepository extends JpaRepository<StoryboardVideoTask, Long> {
    
    Optional<StoryboardVideoTask> findByTaskId(String taskId);
    
    List<StoryboardVideoTask> findByUsernameOrderByCreatedAtDesc(String username);
    
    Page<StoryboardVideoTask> findByUsernameOrderByCreatedAtDesc(String username, Pageable pageable);
    
    List<StoryboardVideoTask> findByStatus(StoryboardVideoTask.TaskStatus status);
    
    /**
     * 查找超时的分镜视频任务
     * 条件：状态为PROCESSING，且更新时间超过指定时间
     * 使用updatedAt而非createdAt，因为视频生成可能在分镜图生成后很久才开始
     */
    @Query("SELECT t FROM StoryboardVideoTask t WHERE t.status = :status " +
           "AND t.updatedAt < :timeoutTime")
    List<StoryboardVideoTask> findTimeoutTasks(
        @Param("status") StoryboardVideoTask.TaskStatus status,
        @Param("timeoutTime") LocalDateTime timeoutTime
    );
}
