package com.gnx.telemedicine.repository;

import com.gnx.telemedicine.model.HipaaAuditLog;
import com.gnx.telemedicine.model.enums.ActionType;
import org.springframework.data.jpa.repository.EntityGraph;
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.List;
import java.util.UUID;

@Repository
public interface HipaaAuditLogRepository extends JpaRepository<HipaaAuditLog, UUID> {
    
    @EntityGraph(attributePaths = {"user", "patient", "patient.user"})
    List<HipaaAuditLog> findByPatientIdOrderByTimestampDesc(UUID patientId);
    
    @EntityGraph(attributePaths = {"user", "patient", "patient.user"})
    List<HipaaAuditLog> findByUserIdOrderByTimestampDesc(UUID userId);
    
    void deleteByUserId(UUID userId);
    
    void deleteByPatientId(UUID patientId);
    
    @EntityGraph(attributePaths = {"user", "patient", "patient.user"})
    List<HipaaAuditLog> findByResourceTypeAndResourceIdOrderByTimestampDesc(String resourceType, UUID resourceId);
    
    @EntityGraph(attributePaths = {"user", "patient", "patient.user"})
    @Query("SELECT hal FROM HipaaAuditLog hal WHERE hal.patient.id = :patientId AND hal.timestamp >= :startDate AND hal.timestamp <= :endDate ORDER BY hal.timestamp DESC")
    List<HipaaAuditLog> findByPatientIdAndDateRange(@Param("patientId") UUID patientId, @Param("startDate") Instant startDate, @Param("endDate") Instant endDate);
    
    @EntityGraph(attributePaths = {"user", "patient", "patient.user"})
    @Query("SELECT hal FROM HipaaAuditLog hal WHERE hal.user.id = :userId AND hal.actionType = :actionType ORDER BY hal.timestamp DESC")
    List<HipaaAuditLog> findByUserIdAndActionType(@Param("userId") UUID userId, @Param("actionType") ActionType actionType);
    
    @Query("SELECT COUNT(hal) FROM HipaaAuditLog hal WHERE hal.patient.id = :patientId AND hal.timestamp >= :startDate")
    Long countAccessesByPatientIdSince(@Param("patientId") UUID patientId, @Param("startDate") Instant startDate);
}

