package com.ttstd.signaling.repository;

import com.ttstd.signaling.model.AuditLog;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;

/**
 * 审计日志持久化仓库。
 */
public interface AuditLogRepository extends JpaRepository<AuditLog, Long> {

    /**
     * 按可选条件分页查询，任一参数为 null 时视为不过滤。
     */
    @Query("""
            SELECT a FROM AuditLog a
            WHERE (:actorId IS NULL OR a.actorId = :actorId)
              AND (:action  IS NULL OR a.action  = :action)
              AND (:result  IS NULL OR a.result  = :result)
            ORDER BY a.id DESC
            """)
    Page<AuditLog> search(@Param("actorId") String actorId,
                          @Param("action") String action,
                          @Param("result") String result,
                          Pageable pageable);

    /** 清理指定时间点之前的历史日志，返回删除条数。 */
    @Modifying
    @Query("DELETE FROM AuditLog a WHERE a.createdAt < :before")
    int deleteOlderThan(@Param("before") Instant before);
}
