package com.example.demo.repository;

import com.example.demo.model.TextToVideoTask;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 文生视频任务Repository
 */
@Repository
public interface TextToVideoTaskRepository extends JpaRepository<TextToVideoTask, Long> {
    
    /**
     * 根据任务ID查找任务
     */
    Optional<TextToVideoTask> findByTaskId(String taskId);
    
    /**
     * 根据用户名查找任务列表（按创建时间倒序）
     */
    List<TextToVideoTask> findByUsernameOrderByCreatedAtDesc(String username);
    
    /**
     * 根据用户名分页查找任务列表
     */
    Page<TextToVideoTask> findByUsernameOrderByCreatedAtDesc(String username, Pageable pageable);
    
    /**
     * 根据任务ID和用户名查找任务
     */
    Optional<TextToVideoTask> findByTaskIdAndUsername(String taskId, String username);
    
    /**
     * 统计用户任务数量
     */
    long countByUsername(String username);
    
    /**
     * 根据状态查找任务列表
     */
    List<TextToVideoTask> findByStatus(TextToVideoTask.TaskStatus status);
    
    /**
     * 根据用户名和状态查找任务列表
     */
    List<TextToVideoTask> findByUsernameAndStatus(String username, TextToVideoTask.TaskStatus status);
    
    /**
     * 查找需要处理的任务（状态为PENDING或PROCESSING）
     */
    @Query("SELECT t FROM TextToVideoTask t WHERE t.status IN ('PENDING', 'PROCESSING') ORDER BY t.createdAt ASC")
    List<TextToVideoTask> findPendingTasks();
    
    /**
     * 查找指定状态的任务列表
     */
    @Query("SELECT t FROM TextToVideoTask t WHERE t.status = :status ORDER BY t.createdAt DESC")
    List<TextToVideoTask> findByStatusOrderByCreatedAtDesc(@Param("status") TextToVideoTask.TaskStatus status);
    
    /**
     * 统计用户各状态任务数量
     */
    @Query("SELECT t.status, COUNT(t) FROM TextToVideoTask t WHERE t.username = :username GROUP BY t.status")
    List<Object[]> countTasksByStatus(@Param("username") String username);
    
    /**
     * 查找用户最近的任务
     */
    @Query("SELECT t FROM TextToVideoTask t WHERE t.username = :username ORDER BY t.createdAt DESC")
    List<TextToVideoTask> findRecentTasksByUsername(@Param("username") String username, Pageable pageable);
    
    /**
     * 删除过期的任务（超过30天且已完成或失败）
     */
    @Modifying
    @Query("DELETE FROM TextToVideoTask t WHERE t.createdAt < :expiredDate AND t.status IN ('COMPLETED', 'FAILED', 'CANCELLED')")
    int deleteExpiredTasks(@Param("expiredDate") java.time.LocalDateTime expiredDate);

    /**
     * 根据状态删除任务
     */
    @Modifying
    @Query("DELETE FROM TextToVideoTask t WHERE t.status = :status")
    int deleteByStatus(@Param("status") String status);
}

