package com.pharmacopoeia.repository;

import com.pharmacopoeia.entity.Message;
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.Query;
import org.springframework.data.repository.query.Param;

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

public interface MessageRepository extends JpaRepository<Message, Long> {
    List<Message> findByConversationIdOrderByCreatedAtAsc(String conversationId);

    long countByConversationId(String conversationId);
    long countByRole(String role);

    @Query("SELECT COUNT(m) FROM Message m WHERE m.role = 'user' AND m.createdAt > :since")
    long countUserMessagesSince(@Param("since") Instant since);

    @Query("SELECT m.conversationId, COUNT(m) FROM Message m WHERE m.conversationId IN :cids GROUP BY m.conversationId")
    List<Object[]> countByConversationIds(@Param("cids") List<String> cids);

    /** 按用户获取最近消息（倒序），用于前端恢复对话 */
    @Query("SELECT m FROM Message m WHERE m.userKey = :userKey ORDER BY m.createdAt DESC")
    Page<Message> findRecentByUserKey(@Param("userKey") String userKey, Pageable pageable);
}