package com.pablotj.ai.chat.infrastructure.persistence.repository;

import com.pablotj.ai.chat.infrastructure.persistence.entity.ConversationEntity;
import com.pablotj.ai.chat.infrastructure.persistence.entity.ConversationStatusEntity;
import java.util.List;
import java.util.Optional;
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;

/**
 * JPA repository interface for conversation entities.
 */
@Repository
public interface ConversationJpaRepository extends JpaRepository<ConversationEntity, Long> {

    /**
     * Finds a conversation by its UUID.
     */
    Optional<ConversationEntity> findByUuid(String uuid);

    /**
     * Finds conversations by status ordered by creation date descending.
     */
    List<ConversationEntity> findByStatusOrderByCreatedAtDesc(ConversationStatusEntity status);

    /**
     * Finds all active conversations with their message count.
     */
    @Query("SELECT c FROM ConversationEntity c WHERE c.status = :status ORDER BY c.createdAt DESC")
    List<ConversationEntity> findActiveConversationsOrderedByCreationDate(@Param("status") ConversationStatusEntity status);

    /**
     * Counts conversations by status.
     */
    long countByStatus(ConversationStatusEntity status);

    /**
     * Checks if a conversation exists by UUID.
     */
    boolean existsByUuid(String uuid);

    /**
     * Deletes a conversation by UUID.
     */
    void deleteByUuid(String uuid);

    /**
     * Finds conversations with message count greater than specified value.
     */
    @Query("SELECT c FROM ConversationEntity c WHERE SIZE(c.messages) > :messageCount")
    List<ConversationEntity> findConversationsWithMoreThanMessages(@Param("messageCount") int messageCount);
}
