package ru.soune.nocopy.repository;

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 ru.soune.nocopy.entity.search.GlobalSearchTask;

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

@Repository
public interface GlobalSearchTaskRepository extends JpaRepository<GlobalSearchTask, String> {
    Optional<GlobalSearchTask> findByTaskIdAndUserId(String taskId, Long userId);

    Optional<GlobalSearchTask> findByUserIdAndStatus(Long userId, String status);

    List<GlobalSearchTask> findByUserIdOrderByCreatedAtDesc(Long userId);

    List<GlobalSearchTask> findByUserIdAndCreatedAtAfterOrderByCreatedAtDesc(Long userId, LocalDateTime date);

    @Query("SELECT COUNT(t) FROM GlobalSearchTask t WHERE t.userId IN :userIds")
    long countByUserId(@Param("userIds") List<Long> userIds);

    @Query("SELECT t.status, COUNT(t) FROM GlobalSearchTask t WHERE t.userId IN :userIds GROUP BY t.status")
    List<Object[]> countByStatusAndUserId(@Param("userIds") List<Long> userIds);

    @Query("SELECT t FROM GlobalSearchTask t WHERE t.userId = :userId ORDER BY t.createdAt DESC")
    List<GlobalSearchTask> findTopByUserIdOrderByCreatedAtDesc(@Param("userId") Long userId,
                                                               org.springframework.data.domain.Pageable pageable);
}

