package com.honey.honey.repository;

import com.honey.honey.model.SupportMessage;
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 org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SupportMessageRepository extends JpaRepository<SupportMessage, Long> {
    
    /**
     * Find all messages for a ticket, ordered by created_at ASC.
     */
    List<SupportMessage> findByTicketIdOrderByCreatedAtAsc(Long ticketId);
    
    /**
     * Count messages for a ticket.
     */
    long countByTicketId(Long ticketId);
    
    /**
     * Find the last message for a user in a specific ticket (for rate limiting per ticket).
     * Returns only the most recent message (limit 1).
     */
    @Query("SELECT m FROM SupportMessage m WHERE m.ticket.id = :ticketId AND m.user.id = :userId ORDER BY m.createdAt DESC")
    List<SupportMessage> findLastMessageByTicketIdAndUserId(@Param("ticketId") Long ticketId, @Param("userId") Integer userId, Pageable pageable);
}

