package de.assecutor.votianlt.repository;

import de.assecutor.votianlt.model.Message;
import de.assecutor.votianlt.model.MessageDeliveryStatus;
import de.assecutor.votianlt.model.MessageOrigin;
import de.assecutor.votianlt.model.MessageType;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface MessageRepository extends MongoRepository<Message, ObjectId> {

    /**
     * Find all messages for a specific receiver (AppUser ID), ordered by creation
     * time ascending (oldest first)
     */
    List<Message> findByReceiverOrderByCreatedAtAsc(String receiver);

    /**
     * Find all messages for a specific receiver (AppUser ID), ordered by creation
     * time descending (newest first)
     */
    List<Message> findByReceiverOrderByCreatedAtDesc(String receiver);

    /**
     * Find all unread messages for a specific receiver (AppUser ID)
     */
    List<Message> findByReceiverAndIsReadFalseOrderByCreatedAtDesc(String receiver);

    /**
     * Find all messages related to a specific job
     */
    List<Message> findByJobIdOrderByCreatedAtDesc(ObjectId jobId);

    /**
     * Find all messages of a specific type for a receiver (AppUser ID)
     */
    List<Message> findByReceiverAndMessageTypeOrderByCreatedAtDesc(String receiver, MessageType messageType);

    /**
     * Find all messages by origin (CLIENT/SERVER)
     */
    List<Message> findByOriginOrderByCreatedAtDesc(MessageOrigin origin);

    /**
     * Find all unread messages count for a specific receiver (AppUser ID)
     */
    long countByReceiverAndIsReadFalse(String receiver);

    /**
     * Find all messages for a specific receiver (AppUser ID) and job
     */
    List<Message> findByReceiverAndJobIdOrderByCreatedAtDesc(String receiver, ObjectId jobId);

    /**
     * Find all messages (for admin/overview), ordered by creation time descending
     */
    List<Message> findAllByOrderByCreatedAtDesc();

    /**
     * Find all messages with a specific delivery status for a receiver
     */
    List<Message> findByReceiverAndDeliveryStatusOrderByCreatedAtAsc(String receiver,
            MessageDeliveryStatus deliveryStatus);

    Optional<Message> findFirstByReceiverAndOriginAndClientMessageId(String receiver, MessageOrigin origin,
            String clientMessageId);

    /**
     * Find all undelivered messages (NOTSEND status) for a receiver
     */
    default List<Message> findUndeliveredMessagesForReceiver(String receiver) {
        return findByReceiverAndDeliveryStatusOrderByCreatedAtAsc(receiver, MessageDeliveryStatus.NOTSEND);
    }
}
