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

import com.qqchen.deploy.backend.deploy.entity.ServerAlertLog;
import com.qqchen.deploy.backend.framework.enums.MonitorMetricEnum;
import com.qqchen.deploy.backend.framework.enums.ServerAlertStatusEnum;
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;
import java.util.Optional;

/**
 * 服务器告警记录Repository
 */
@Repository
public interface IServerAlertLogRepository extends JpaRepository<ServerAlertLog, Long> {

    /**
     * 查询指定服务器的指定状态告警
     */
    List<ServerAlertLog> findByServerIdAndStatus(Long serverId, ServerAlertStatusEnum status);

    /**
     * 查询指定服务器在指定时间范围内的告警记录
     */
    List<ServerAlertLog> findByServerIdAndAlertTimeBetweenOrderByAlertTimeDesc(
        Long serverId, LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 查询指定服务器、规则、告警类型的活跃或待处理告警
     * 用于判断是否已存在未解决的告警
     */
    @Query("SELECT a FROM ServerAlertLog a WHERE a.serverId = :serverId " +
           "AND a.ruleId = :ruleId " +
           "AND a.alertType = :alertType " +
           "AND a.status IN (com.qqchen.deploy.backend.framework.enums.ServerAlertStatusEnum.PENDING, " +
           "                 com.qqchen.deploy.backend.framework.enums.ServerAlertStatusEnum.ACTIVE) " +
           "ORDER BY a.alertTime DESC")
    Optional<ServerAlertLog> findActiveOrPendingAlert(
        @Param("serverId") Long serverId,
        @Param("ruleId") Long ruleId,
        @Param("alertType") MonitorMetricEnum alertType
    );

    /**
     * 删除指定服务器的所有告警记录
     */
    @Modifying
    @Query("DELETE FROM ServerAlertLog l WHERE l.serverId = :serverId")
    int deleteByServerId(@Param("serverId") Long serverId);
}
