package com.example.demo.repository;

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

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.CompletedTaskArchive;

/**
 * 成功任务归档Repository
 */
@Repository
public interface CompletedTaskArchiveRepository extends JpaRepository<CompletedTaskArchive, Long> {
    
    /**
     * 根据用户名查找归档任务
     */
    List<CompletedTaskArchive> findByUsernameOrderByArchivedAtDesc(String username);
    
    /**
     * 根据用户名分页查找归档任务
     */
    Page<CompletedTaskArchive> findByUsernameOrderByArchivedAtDesc(String username, Pageable pageable);
    
    /**
     * 根据任务类型查找归档任务
     */
    List<CompletedTaskArchive> findByTaskTypeOrderByArchivedAtDesc(String taskType);
    
    /**
     * 根据用户名和任务类型查找归档任务
     */
    List<CompletedTaskArchive> findByUsernameAndTaskTypeOrderByArchivedAtDesc(String username, String taskType);
    
    /**
     * 统计用户归档任务数量
     */
    long countByUsername(String username);
    
    /**
     * 统计任务类型归档数量
     */
    long countByTaskType(String taskType);
    
    /**
     * 查找指定时间范围内的归档任务
     */
    @Query("SELECT c FROM CompletedTaskArchive c WHERE c.archivedAt BETWEEN :startDate AND :endDate ORDER BY c.archivedAt DESC")
    List<CompletedTaskArchive> findByArchivedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                                       @Param("endDate") LocalDateTime endDate);
    
    /**
     * 查找指定时间范围内的归档任务（分页）
     */
    @Query("SELECT c FROM CompletedTaskArchive c WHERE c.archivedAt BETWEEN :startDate AND :endDate ORDER BY c.archivedAt DESC")
    Page<CompletedTaskArchive> findByArchivedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                                       @Param("endDate") LocalDateTime endDate, 
                                                       Pageable pageable);
    
    /**
     * 统计指定时间范围内的归档任务数量
     */
    @Query("SELECT COUNT(c) FROM CompletedTaskArchive c WHERE c.archivedAt BETWEEN :startDate AND :endDate")
    long countByArchivedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                 @Param("endDate") LocalDateTime endDate);
    
    /**
     * 查找超过指定天数的归档任务
     */
    @Query("SELECT c FROM CompletedTaskArchive c WHERE c.archivedAt < :cutoffDate")
    List<CompletedTaskArchive> findOlderThan(@Param("cutoffDate") LocalDateTime cutoffDate);
    
    /**
     * 删除超过指定天数的归档任务
     */
    @Query("DELETE FROM CompletedTaskArchive c WHERE c.archivedAt < :cutoffDate")
    int deleteOlderThan(@Param("cutoffDate") LocalDateTime cutoffDate);
}
