package com.storycove.repository;

import com.storycove.entity.Tag;
import org.springframework.data.domain.Page;
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;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface TagRepository extends JpaRepository<Tag, UUID> {
    
    Optional<Tag> findByName(String name);
    
    Optional<Tag> findByNameIgnoreCase(String name);
    
    boolean existsByName(String name);
    
    boolean existsByNameIgnoreCase(String name);
    
    List<Tag> findByNameContainingIgnoreCase(String name);
    
    Page<Tag> findByNameContainingIgnoreCase(String name, Pageable pageable);
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.stories) > 0 ORDER BY SIZE(t.stories) DESC")
    List<Tag> findUsedTags();
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.stories) > 0 ORDER BY SIZE(t.stories) DESC")
    Page<Tag> findUsedTags(Pageable pageable);
    
    @Query("SELECT t FROM Tag t ORDER BY SIZE(t.stories) DESC")
    List<Tag> findMostUsedTags();
    
    @Query("SELECT t FROM Tag t ORDER BY SIZE(t.stories) DESC")
    Page<Tag> findMostUsedTags(Pageable pageable);
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.stories) >= :minUsage ORDER BY SIZE(t.stories) DESC")
    List<Tag> findTagsByMinimumUsage(@Param("minUsage") Integer minUsage);
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.stories) = 0")
    List<Tag> findUnusedTags();
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.stories) > :threshold ORDER BY SIZE(t.stories) DESC")
    List<Tag> findPopularTags(@Param("threshold") Integer threshold);
    
    @Query("SELECT COUNT(t) FROM Tag t WHERE t.createdAt >= :cutoffDate")
    long countRecentTags(@Param("cutoffDate") java.time.LocalDateTime cutoffDate);
    
    @Query("SELECT t FROM Tag t WHERE t.name IN :names")
    List<Tag> findByNames(@Param("names") List<String> names);
    
    List<Tag> findByNameStartingWithIgnoreCase(String prefix);
    
    @Query("SELECT COUNT(t) FROM Tag t WHERE SIZE(t.stories) > 0")
    long countUsedTags();
    
    @Query("SELECT t FROM Tag t WHERE SIZE(t.collections) > 0 ORDER BY SIZE(t.collections) DESC, t.name ASC")
    List<Tag> findTagsUsedByCollections();
}