package com.gcsc.connection.monitoring.repository;

import com.gcsc.connection.monitoring.entity.SnpServiceHealthLog;
import org.springframework.data.domain.Pageable;
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 java.time.LocalDateTime;
import java.util.List;

public interface SnpServiceHealthLogRepository extends JpaRepository<SnpServiceHealthLog, Long> {

    List<SnpServiceHealthLog> findByServiceServiceIdOrderByCheckedAtDesc(Long serviceId);

    List<SnpServiceHealthLog> findByServiceServiceIdOrderByCheckedAtDesc(Long serviceId, Pageable pageable);

    /** 일별 uptime 비율 (service_id별, 90일) */
    @Query(value = "SELECT DATE(checked_at) as check_date, " +
        "COUNT(*) as total, " +
        "COUNT(CASE WHEN current_status = 'UP' THEN 1 END) as up_count " +
        "FROM common.snp_service_health_log " +
        "WHERE service_id = :serviceId AND checked_at >= :since " +
        "GROUP BY DATE(checked_at) ORDER BY check_date", nativeQuery = true)
    List<Object[]> findDailyUptime(@Param("serviceId") Long serviceId, @Param("since") LocalDateTime since);

    /** 90일 이전 데이터 삭제 */
    @Modifying
    @Query("DELETE FROM SnpServiceHealthLog h WHERE h.checkedAt < :before")
    int deleteOlderThan(@Param("before") LocalDateTime before);
}
