package de.cannamanage.service.repository;

import de.cannamanage.domain.entity.AuditEvent;
import de.cannamanage.domain.enums.AuditEventType;
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;
import java.util.UUID;

@Repository
public interface AuditEventRepository extends JpaRepository<AuditEvent, UUID> {

    Page<AuditEvent> findByTenantIdOrderByTimestampDesc(UUID tenantId, Pageable pageable);

    @Query("""
        SELECT a FROM AuditEvent a
        WHERE a.tenantId = :tenantId
          AND (:eventType IS NULL OR a.eventType = :eventType)
          AND (:entityType IS NULL OR a.entityType = :entityType)
          AND (:actorId IS NULL OR a.actorId = :actorId)
          AND (:from IS NULL OR a.timestamp >= :from)
          AND (:to IS NULL OR a.timestamp <= :to)
        ORDER BY a.timestamp DESC
    """)
    Page<AuditEvent> findFiltered(
            @Param("tenantId") UUID tenantId,
            @Param("eventType") AuditEventType eventType,
            @Param("entityType") String entityType,
            @Param("actorId") UUID actorId,
            @Param("from") Instant from,
            @Param("to") Instant to,
            Pageable pageable
    );

    @Query("""
        SELECT a FROM AuditEvent a
        WHERE a.tenantId = :tenantId
          AND a.timestamp >= :from
          AND a.timestamp <= :to
        ORDER BY a.timestamp DESC
    """)
    java.util.List<AuditEvent> findByTenantIdAndTimestampRange(
            @Param("tenantId") UUID tenantId,
            @Param("from") Instant from,
            @Param("to") Instant to
    );
}
