package com.storycove.repository;

import com.storycove.entity.ReadingPosition;
import com.storycove.entity.Story;
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.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface ReadingPositionRepository extends JpaRepository<ReadingPosition, UUID> {
    
    Optional<ReadingPosition> findByStoryId(UUID storyId);
    
    Optional<ReadingPosition> findByStory(Story story);
    
    List<ReadingPosition> findByStoryIdIn(List<UUID> storyIds);
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.story.id = :storyId ORDER BY rp.updatedAt DESC")
    List<ReadingPosition> findByStoryIdOrderByUpdatedAtDesc(@Param("storyId") UUID storyId);
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete >= :minPercentage")
    List<ReadingPosition> findByMinimumPercentageComplete(@Param("minPercentage") Double minPercentage);
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete >= 95.0")
    List<ReadingPosition> findCompletedReadings();
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete > 0 AND rp.percentageComplete < 95.0")
    List<ReadingPosition> findInProgressReadings();
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.updatedAt >= :since ORDER BY rp.updatedAt DESC")
    List<ReadingPosition> findRecentlyUpdated(@Param("since") LocalDateTime since);
    
    @Query("SELECT rp FROM ReadingPosition rp ORDER BY rp.updatedAt DESC")
    List<ReadingPosition> findAllOrderByUpdatedAtDesc();
    
    @Query("SELECT COUNT(rp) FROM ReadingPosition rp WHERE rp.percentageComplete >= 95.0")
    long countCompletedReadings();
    
    @Query("SELECT COUNT(rp) FROM ReadingPosition rp WHERE rp.percentageComplete > 0 AND rp.percentageComplete < 95.0")
    long countInProgressReadings();
    
    @Query("SELECT AVG(rp.percentageComplete) FROM ReadingPosition rp WHERE rp.percentageComplete > 0")
    Double findAverageReadingProgress();
    
    @Query("SELECT rp FROM ReadingPosition rp WHERE rp.epubCfi IS NOT NULL")
    List<ReadingPosition> findPositionsWithEpubCfi();
    
    boolean existsByStoryId(UUID storyId);
    
    void deleteByStoryId(UUID storyId);
}