package com.storycove.repository;

import com.storycove.entity.Collection;
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;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface CollectionRepository extends JpaRepository<Collection, UUID> {
    
    /**
     * Find collection by ID with tags eagerly loaded
     * Used for detailed collection retrieval
     */
    @Query("SELECT c FROM Collection c LEFT JOIN FETCH c.tags WHERE c.id = :id")
    Optional<Collection> findByIdWithTags(@Param("id") UUID id);
    
    /**
     * Find collection by ID with full story details
     * Used for collection detail view with story list
     */
    @Query("SELECT c FROM Collection c " +
           "LEFT JOIN FETCH c.collectionStories cs " +
           "LEFT JOIN FETCH cs.story s " +
           "LEFT JOIN FETCH s.author " +
           "LEFT JOIN FETCH c.tags " +
           "WHERE c.id = :id " +
           "ORDER BY cs.position ASC")
    Optional<Collection> findByIdWithStoriesAndTags(@Param("id") UUID id);
    
    /**
     * Count all collections for statistics
     */
    long countByIsArchivedFalse();
    
    /**
     * Find all collections with basic info (for batch operations)
     * NOTE: This method should only be used for operations that require all collections
     * For search/filter/list operations, use TypesenseService instead
     */
    @Query("SELECT c FROM Collection c WHERE c.isArchived = false ORDER BY c.updatedAt DESC")
    List<Collection> findAllActiveCollections();
    
    /**
     * Find all collections with tags for reindexing operations
     */
    @Query("SELECT c FROM Collection c LEFT JOIN FETCH c.tags ORDER BY c.updatedAt DESC")
    List<Collection> findAllWithTags();
    
}