package ru.soune.nocopy.repository;

import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import ru.soune.nocopy.entity.monitoring.FileMonitoringEntity;
import ru.soune.nocopy.entity.monitoring.MonitoringType;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface FileMonitoringRepository extends JpaRepository<FileMonitoringEntity, String> {

    Optional<FileMonitoringEntity> findByFileId(String fileId);

    List<FileMonitoringEntity> findByUserIdAndIsActiveTrue(Long userId);

    @Query("SELECT fm FROM FileMonitoringEntity fm WHERE fm.isActive = true AND fm.monitoringType != 'NONE' AND fm.nextRun <= :now")
    List<FileMonitoringEntity> findReadyForRun(@Param("now") LocalDateTime now);

    List<FileMonitoringEntity> findByMonitoringTypeAndIsActiveTrue(MonitoringType type);

    @Query("SELECT COUNT(m) FROM FileMonitoringEntity m " +
            "WHERE m.userId IN :userIds " +
            "AND m.monitoringType = :monitoringType " +
            "AND m.isActive = true")
    long countByUserIdsAndMonitoringType(@Param("userIds") List<Long> userIds,
                                         @Param("monitoringType") MonitoringType monitoringType);

    @Modifying
    @Transactional
    @Query("DELETE FROM FileMonitoringEntity f WHERE f.file.id IN :fileIds")
    void deleteAllByFileIdIn(@Param("fileIds") List<String> fileIds);
}
