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

/**
 * 失败任务清理日志Repository
 */
@Repository
public interface FailedTaskCleanupLogRepository extends JpaRepository<FailedTaskCleanupLog, Long> {
    
    /**
     * 根据用户名查找清理日志
     */
    List<FailedTaskCleanupLog> findByUsernameOrderByCleanedAtDesc(String username);
    
    /**
     * 根据用户名分页查找清理日志
     */
    Page<FailedTaskCleanupLog> findByUsernameOrderByCleanedAtDesc(String username, Pageable pageable);
    
    /**
     * 根据任务类型查找清理日志
     */
    List<FailedTaskCleanupLog> findByTaskTypeOrderByCleanedAtDesc(String taskType);
    
    /**
     * 根据用户名和任务类型查找清理日志
     */
    List<FailedTaskCleanupLog> findByUsernameAndTaskTypeOrderByCleanedAtDesc(String username, String taskType);
    
    /**
     * 统计用户清理日志数量
     */
    long countByUsername(String username);
    
    /**
     * 统计任务类型清理日志数量
     */
    long countByTaskType(String taskType);
    
    /**
     * 查找指定时间范围内的清理日志
     */
    @Query("SELECT f FROM FailedTaskCleanupLog f WHERE f.cleanedAt BETWEEN :startDate AND :endDate ORDER BY f.cleanedAt DESC")
    List<FailedTaskCleanupLog> findByCleanedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                                     @Param("endDate") LocalDateTime endDate);
    
    /**
     * 查找指定时间范围内的清理日志（分页）
     */
    @Query("SELECT f FROM FailedTaskCleanupLog f WHERE f.cleanedAt BETWEEN :startDate AND :endDate ORDER BY f.cleanedAt DESC")
    Page<FailedTaskCleanupLog> findByCleanedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                                     @Param("endDate") LocalDateTime endDate, 
                                                     Pageable pageable);
    
    /**
     * 统计指定时间范围内的清理日志数量
     */
    @Query("SELECT COUNT(f) FROM FailedTaskCleanupLog f WHERE f.cleanedAt BETWEEN :startDate AND :endDate")
    long countByCleanedAtBetween(@Param("startDate") LocalDateTime startDate, 
                                @Param("endDate") LocalDateTime endDate);
    
    /**
     * 查找超过指定天数的清理日志
     */
    @Query("SELECT f FROM FailedTaskCleanupLog f WHERE f.cleanedAt < :cutoffDate")
    List<FailedTaskCleanupLog> findOlderThan(@Param("cutoffDate") LocalDateTime cutoffDate);
    
    /**
     * 删除超过指定天数的清理日志
     */
    @Query("DELETE FROM FailedTaskCleanupLog f WHERE f.cleanedAt < :cutoffDate")
    int deleteOlderThan(@Param("cutoffDate") LocalDateTime cutoffDate);
}
