package com.qqchen.deploy.backend.deploy.repository;

import com.qqchen.deploy.backend.deploy.entity.ServerMonitor;
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.time.LocalDateTime;
import java.util.List;

/**
 * 服务器监控记录Repository
 */
@Repository
public interface IServerMonitorRepository extends JpaRepository<ServerMonitor, Long> {

    /**
     * 查询指定服务器在指定时间范围内的监控记录
     */
    List<ServerMonitor> findByServerIdAndCollectTimeBetweenOrderByCollectTimeDesc(
        Long serverId, LocalDateTime startTime, LocalDateTime endTime);

    /**
     * 查询指定服务器的最新一条监控记录（用于计算网络流量速率）
     */
    ServerMonitor findFirstByServerIdOrderByCollectTimeDesc(Long serverId);

    /**
     * 删除指定时间之前的监控记录
     */
    @Modifying
    @Query("DELETE FROM ServerMonitor m WHERE m.collectTime < :beforeTime")
    int deleteByCollectTimeBefore(@Param("beforeTime") LocalDateTime beforeTime);

    /**
     * 删除指定服务器的所有监控记录
     */
    @Modifying
    @Query("DELETE FROM ServerMonitor m WHERE m.serverId = :serverId")
    int deleteByServerId(@Param("serverId") Long serverId);

    /**
     * 查询指定服务器最近N条监控记录（按时间倒序）
     * 用于统计连续失败次数
     */
    @Query("SELECT m FROM ServerMonitor m WHERE m.serverId = :serverId ORDER BY m.collectTime DESC")
    List<ServerMonitor> findRecentMonitorRecords(@Param("serverId") Long serverId, org.springframework.data.domain.Pageable pageable);

    /**
     * 查询指定服务器在时间范围内的监控记录（按时间正序）
     * 用于监控数据展示
     * 只查询SUCCESS状态的记录（过滤连接失败的FAILURE记录）
     */
    @Query("SELECT m FROM ServerMonitor m WHERE m.serverId = :serverId " +
           "AND m.collectTime >= :startTime AND m.collectTime <= :endTime " +
           "AND m.status = 'SUCCESS' " +
           "ORDER BY m.collectTime ASC")
    List<ServerMonitor> findByServerIdAndTimeRange(
        @Param("serverId") Long serverId,
        @Param("startTime") LocalDateTime startTime,
        @Param("endTime") LocalDateTime endTime
    );
}
