package com.storycove.repository;

import com.storycove.entity.Series;
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 SeriesRepository extends JpaRepository<Series, UUID> {
    
    Optional<Series> findByName(String name);
    
    boolean existsByName(String name);
    
    List<Series> findByNameContainingIgnoreCase(String name);
    
    Page<Series> findByNameContainingIgnoreCase(String name, Pageable pageable);
    
    @Query("SELECT s FROM Series s WHERE SIZE(s.stories) > 0")
    List<Series> findSeriesWithStories();
    
    @Query("SELECT s FROM Series s WHERE SIZE(s.stories) > 0")
    Page<Series> findSeriesWithStories(Pageable pageable);
    
    @Query("SELECT s FROM Series s JOIN s.stories st GROUP BY s.id ORDER BY COUNT(st) DESC")
    List<Series> findLongestSeries();
    
    @Query("SELECT s FROM Series s JOIN s.stories st GROUP BY s.id ORDER BY COUNT(st) DESC")
    Page<Series> findLongestSeries(Pageable pageable);
    
    @Query("SELECT s FROM Series s WHERE SIZE(s.stories) >= :minParts ORDER BY SIZE(s.stories) DESC")
    List<Series> findByMinimumParts(@Param("minParts") Integer minParts);
    
    @Query("SELECT s FROM Series s WHERE SIZE(s.stories) = 0")
    List<Series> findEmptySeries();
    
    @Query("SELECT s FROM Series s JOIN s.stories st GROUP BY s.id ORDER BY AVG(st.rating) DESC")
    List<Series> findTopRatedSeries();
    
    @Query("SELECT s FROM Series s JOIN s.stories st GROUP BY s.id ORDER BY AVG(st.rating) DESC")
    Page<Series> findTopRatedSeries(Pageable pageable);
    
    @Query("SELECT COUNT(s) FROM Series s WHERE s.createdAt >= :cutoffDate")
    long countRecentSeries(@Param("cutoffDate") java.time.LocalDateTime cutoffDate);
    
    @Query("SELECT COUNT(s) FROM Series s WHERE SIZE(s.stories) > 0")
    long countSeriesWithStories();
}