package ru.soune.nocopy.repository;

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.Query;
import org.springframework.data.repository.query.Param;
import ru.soune.nocopy.entity.notification.Notification;
import ru.soune.nocopy.entity.notification.NotificationStatus;
import ru.soune.nocopy.entity.notification.NotificationType;
import ru.soune.nocopy.entity.user.User;

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

public interface NotificationRepository extends JpaRepository<Notification, Long> {
    Page<Notification> findByUser(User user, Pageable pageable);

    Page<Notification> findByUserAndNotificationTypeIn(User user, List<NotificationType> types, Pageable pageable);

    Page<Notification> findByUserAndStatusIn(User user, List<NotificationStatus> statuses, Pageable pageable);

    Page<Notification> findByUserAndNotificationTypeInAndStatusIn(User user, List<NotificationType> types,
                                                                  List<NotificationStatus> statuses,
                                                                  Pageable pageable);

    List<Notification> findTop5ByUserAndStatusOrderByCreatedAtDesc(User user, NotificationStatus status);

    long countByUserAndStatus(User user, NotificationStatus status);

    @Modifying
    @Query("UPDATE Notification n SET n.status = :newStatus , n.updatedAt = :updateTime WHERE n.id IN :ids AND n.user = :user AND " +
            "n.status = :oldStatus")
    int updateStatus(@Param("ids") List<Long> ids,
                     @Param("user") User user,
                     @Param("oldStatus") NotificationStatus oldStatus,
                     @Param("newStatus") NotificationStatus newStatus,
                     @Param("updateTime") LocalDateTime updateTime);

    Page<Notification> getNotificationsByUser(User user, Pageable pageable);
}
