package com.pharmacopoeia.repository;

import com.pharmacopoeia.entity.QuickAskAuditLog;
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 java.time.Instant;

@Repository
public interface QuickAskAuditLogRepository extends JpaRepository<QuickAskAuditLog, Long> {

    Page<QuickAskAuditLog> findAllByOrderByCreatedAtDesc(Pageable pageable);

    /**
     * 按操作类型筛选审计日志（action = CREATE / UPDATE / DELETE）
     * 前端 auditLog 接口可传 action 参数，后端自动使用此方法查询
     */
    Page<QuickAskAuditLog> findByActionOrderByCreatedAtDesc(String action, Pageable pageable);

    @Query("SELECT a FROM QuickAskAuditLog a WHERE "
         + "(:action IS NULL OR a.action = :action) AND "
         + "(:startTime IS NULL OR a.createdAt >= :startTime) AND "
         + "(:endTime IS NULL OR a.createdAt < :endTime) "
         + "ORDER BY a.createdAt DESC")
    Page<QuickAskAuditLog> findByFilters(
            @Param("action") String action,
            @Param("startTime") Instant startTime,
            @Param("endTime") Instant endTime,
            Pageable pageable);
}
