package de.assecutor.votianlt.repository;

import de.assecutor.votianlt.messaging.model.DeliveryStatus;
import de.assecutor.votianlt.messaging.model.PendingDelivery;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

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

/**
 * Repository for PendingDelivery entities.
 */
@Repository
public interface PendingDeliveryRepository extends MongoRepository<PendingDelivery, ObjectId> {

    /**
     * Find pending delivery by message ID
     */
    Optional<PendingDelivery> findByMessageId(String messageId);

    /**
     * Find all deliveries with a specific status
     */
    List<PendingDelivery> findByStatus(DeliveryStatus status);

    /**
     * Find deliveries ready for retry (status = SENT and nextRetryAt is in the past)
     */
    List<PendingDelivery> findByStatusAndNextRetryAtBefore(DeliveryStatus status, LocalDateTime dateTime);

    /**
     * Find acknowledged deliveries older than specified time
     */
    List<PendingDelivery> findByStatusAndAcknowledgedAtBefore(DeliveryStatus status, LocalDateTime dateTime);

    /**
     * Find deliveries with specific statuses that have expired
     */
    List<PendingDelivery> findByStatusInAndExpiresAtBefore(List<DeliveryStatus> statuses, LocalDateTime dateTime);

    /**
     * Find deliveries with specific statuses
     */
    List<PendingDelivery> findByStatusIn(List<DeliveryStatus> statuses);

    /**
     * Find all deliveries for a specific client
     */
    List<PendingDelivery> findByClientId(String clientId);

    /**
     * Find all deliveries for a specific topic
     */
    List<PendingDelivery> findByTopic(String topic);

    /**
     * Count deliveries by status
     */
    long countByStatus(DeliveryStatus status);

    /**
     * Delete deliveries older than specified time
     */
    void deleteByCreatedAtBefore(LocalDateTime dateTime);
}

