package com.erp.systemtool.repository;

import com.erp.systemtool.entity.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.JpaSpecificationExecutor;
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;

/**
 * Repository for AuditLog entity
 */
@Repository
public interface AuditLogRepository extends JpaRepository<AuditLog, Long>,
        JpaSpecificationExecutor<AuditLog> {

    Page<AuditLog> findByTenantIdOrderByCreatedAtDesc(Integer tenantId, Pageable pageable);

    Page<AuditLog> findByUserIdOrderByCreatedAtDesc(Integer userId, Pageable pageable);

    Page<AuditLog> findByModuleAndTenantIdOrderByCreatedAtDesc(String module, Integer tenantId, Pageable pageable);

    Page<AuditLog> findByTargetTypeAndTargetIdOrderByCreatedAtDesc(String targetType, Long targetId, Pageable pageable);

    @Query("SELECT a.module, a.action, COUNT(a) as cnt FROM AuditLog a " +
           "WHERE a.tenantId = :tenantId AND a.createdAt BETWEEN :start AND :end " +
           "GROUP BY a.module, a.action")
    List<Object[]> statsByModuleAndAction(@Param("tenantId") Integer tenantId,
                                           @Param("start") LocalDateTime start,
                                           @Param("end") LocalDateTime end);

    @Query("SELECT a.module, COUNT(a) as cnt FROM AuditLog a " +
           "WHERE a.tenantId = :tenantId AND a.createdAt BETWEEN :start AND :end " +
           "GROUP BY a.module ORDER BY cnt DESC")
    List<Object[]> statsByModule(@Param("tenantId") Integer tenantId,
                                  @Param("start") LocalDateTime start,
                                  @Param("end") LocalDateTime end);

    @Modifying
    @Query("DELETE FROM AuditLog a WHERE a.createdAt < :cutoffDate")
    int deleteOlderThan(@Param("cutoffDate") LocalDateTime cutoffDate);
}
