package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.NotificationEntity;
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 org.springframework.stereotype.Repository;

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

/**
 * 通知Repository
 */
@Repository
public interface NotificationRepository extends JpaRepository<NotificationEntity, Long> {

    /**
     * 根据用户ID查询通知列表
     */
    List<NotificationEntity> findByUserIdOrderByCreatedAtDesc(Long userId);

    /**
     * 分页查询用户通知
     */
    Page<NotificationEntity> findByUserId(Long userId, Pageable pageable);

    /**
     * 查询用户未读通知数量
     */
    long countByUserIdAndIsReadFalse(Long userId);

    /**
     * 查询用户未读通知
     */
    List<NotificationEntity> findByUserIdAndIsReadFalse(Long userId);

    /**
     * 标记用户所有通知为已读
     */
    @Modifying
    @Query("UPDATE NotificationEntity n SET n.isRead = true, n.readAt = :readAt WHERE n.userId = :userId AND n.isRead = false")
    int markAllAsReadByUserId(@Param("userId") Long userId, @Param("readAt") LocalDateTime readAt);

    /**
     * 根据用户ID和类型查询通知
     */
    List<NotificationEntity> findByUserIdAndTypeOrderByCreatedAtDesc(Long userId, String type);

    /**
     * 分页查询用户通知（支持筛选）
     */
    Page<NotificationEntity> findByUserIdAndType(Long userId, String type, Pageable pageable);

    /**
     * 查询用户通知（支持已读/未读筛选）
     */
    Page<NotificationEntity> findByUserIdAndIsRead(Long userId, Boolean isRead, Pageable pageable);

    /**
     * 分页查询用户通知（支持关键词搜索 - 搜索标题和内容）
     */
    @org.springframework.data.jpa.repository.Query("SELECT n FROM NotificationEntity n WHERE n.userId = :userId AND (n.title LIKE %:keyword% OR n.content LIKE %:keyword%)")
    Page<NotificationEntity> findByUserIdAndKeyword(@Param("userId") Long userId, @Param("keyword") String keyword, Pageable pageable);

    /**
     * 分页查询用户通知（支持类型和关键词搜索）
     */
    @org.springframework.data.jpa.repository.Query("SELECT n FROM NotificationEntity n WHERE n.userId = :userId AND n.type = :type AND (n.title LIKE %:keyword% OR n.content LIKE %:keyword%)")
    Page<NotificationEntity> findByUserIdAndTypeAndKeyword(@Param("userId") Long userId, @Param("type") String type, @Param("keyword") String keyword, Pageable pageable);

    /**
     * 分页查询用户通知（支持已读状态和关键词搜索）
     */
    @org.springframework.data.jpa.repository.Query("SELECT n FROM NotificationEntity n WHERE n.userId = :userId AND n.isRead = :isRead AND (n.title LIKE %:keyword% OR n.content LIKE %:keyword%)")
    Page<NotificationEntity> findByUserIdAndIsReadAndKeyword(@Param("userId") Long userId, @Param("isRead") Boolean isRead, @Param("keyword") String keyword, Pageable pageable);
}
