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.UserErrorLog;
import com.example.demo.model.UserErrorLog.ErrorType;

@Repository
public interface UserErrorLogRepository extends JpaRepository<UserErrorLog, Long> {

    // 按用户名查询
    List<UserErrorLog> findByUsernameOrderByCreatedAtDesc(String username);
    
    Page<UserErrorLog> findByUsername(String username, Pageable pageable);

    // 按错误类型查询
    List<UserErrorLog> findByErrorTypeOrderByCreatedAtDesc(ErrorType errorType);
    
    Page<UserErrorLog> findByErrorType(ErrorType errorType, Pageable pageable);

    // 按时间范围查询
    List<UserErrorLog> findByCreatedAtBetweenOrderByCreatedAtDesc(
            LocalDateTime startTime, LocalDateTime endTime);

    // 按用户和时间范围查询
    List<UserErrorLog> findByUsernameAndCreatedAtBetweenOrderByCreatedAtDesc(
            String username, LocalDateTime startTime, LocalDateTime endTime);

    // 按错误来源查询
    List<UserErrorLog> findByErrorSourceOrderByCreatedAtDesc(String errorSource);

    // 按任务ID查询
    List<UserErrorLog> findByTaskIdOrderByCreatedAtDesc(String taskId);

    // 统计：按错误类型分组统计数量
    @Query("SELECT e.errorType, COUNT(e) FROM UserErrorLog e " +
           "WHERE e.createdAt >= :startTime " +
           "GROUP BY e.errorType ORDER BY COUNT(e) DESC")
    List<Object[]> countByErrorType(@Param("startTime") LocalDateTime startTime);

    // 统计：按错误来源分组统计
    @Query("SELECT e.errorSource, COUNT(e) FROM UserErrorLog e " +
           "WHERE e.createdAt >= :startTime " +
           "GROUP BY e.errorSource ORDER BY COUNT(e) DESC")
    List<Object[]> countByErrorSource(@Param("startTime") LocalDateTime startTime);

    // 统计：按日期分组统计错误数量
    @Query("SELECT FUNCTION('DATE', e.createdAt), COUNT(e) FROM UserErrorLog e " +
           "WHERE e.createdAt >= :startTime " +
           "GROUP BY FUNCTION('DATE', e.createdAt) ORDER BY FUNCTION('DATE', e.createdAt) DESC")
    List<Object[]> countByDate(@Param("startTime") LocalDateTime startTime);

    // 统计：指定时间范围内的错误总数
    long countByCreatedAtBetween(LocalDateTime startTime, LocalDateTime endTime);

    // 统计：指定用户的错误总数
    long countByUsername(String username);

    // 删除：清理指定时间之前的错误（用于日志清理）
    void deleteByCreatedAtBefore(LocalDateTime beforeTime);

    // 最近N条错误
    List<UserErrorLog> findTop10ByOrderByCreatedAtDesc();
    
    List<UserErrorLog> findTop50ByOrderByCreatedAtDesc();

    // 用户最近的错误
    List<UserErrorLog> findTop10ByUsernameOrderByCreatedAtDesc(String username);
}
