package com.saas.admin.repository;

import com.saas.shared.audit.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.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;

/**
 * Audit Log Repository
 * 
 * Provides data access for AuditLog entities with support for:
 * - JPA Specifications for dynamic filtering
 * - Pagination and sorting
 * - Aggregation queries for statistics
 */
@Repository
public interface AuditLogRepository extends JpaRepository<AuditLog, Long>, JpaSpecificationExecutor<AuditLog> {

    /**
     * Find all audit logs for a specific tenant
     */
    Page<AuditLog> findByTenantId(String tenantId, Pageable pageable);

    /**
     * Find all audit logs created by a specific user
     */
    Page<AuditLog> findByUserId(Long userId, Pageable pageable);

    /**
     * Find all audit logs for a specific action type
     */
    Page<AuditLog> findByAction(String action, Pageable pageable);

    /**
     * Find all audit logs for a specific entity type
     */
    Page<AuditLog> findByEntityType(String entityType, Pageable pageable);

    /**
     * Find all audit logs within a date range
     */
    Page<AuditLog> findByCreatedAtBetween(LocalDateTime startDate, LocalDateTime endDate, Pageable pageable);

    /**
     * Count audit logs created after a specific date
     */
    long countByCreatedAtAfter(LocalDateTime dateTime);

    /**
     * Count logs by action type for statistics
     */
    @Query("""
        SELECT al.action as action, COUNT(al) as count
        FROM AuditLog al
        GROUP BY al.action
        ORDER BY count DESC
        """)
    List<Object[]> countByActionGrouped();

    /**
     * Count logs by entity type for statistics
     */
    @Query("""
        SELECT al.entityType as entityType, COUNT(al) as count
        FROM AuditLog al
        GROUP BY al.entityType
        ORDER BY count DESC
        """)
    List<Object[]> countByEntityTypeGrouped();

    /**
     * Count logs by tenant for statistics
     */
    @Query("""
        SELECT al.tenantId as tenantId, COUNT(al) as count
        FROM AuditLog al
        WHERE al.tenantId IS NOT NULL
        GROUP BY al.tenantId
        ORDER BY count DESC
        """)
    List<Object[]> countByTenantGrouped();

    /**
     * Count logs by user for statistics
     */
    @Query("""
        SELECT al.userId as userId, COUNT(al) as count
        FROM AuditLog al
        WHERE al.userId IS NOT NULL
        GROUP BY al.userId
        ORDER BY count DESC
        LIMIT 10
        """)
    List<Object[]> countByUserGrouped();
}
