package com.storycove.repository;

import com.storycove.entity.Author;
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 AuthorRepository extends JpaRepository<Author, UUID> {
    
    Optional<Author> findByName(String name);
    
    boolean existsByName(String name);
    
    List<Author> findByNameContainingIgnoreCase(String name);
    
    Page<Author> findByNameContainingIgnoreCase(String name, Pageable pageable);
    
    @Query("SELECT a FROM Author a WHERE SIZE(a.stories) > 0")
    List<Author> findAuthorsWithStories();
    
    @Query("SELECT a FROM Author a WHERE SIZE(a.stories) > 0")
    Page<Author> findAuthorsWithStories(Pageable pageable);
    
    @Query("SELECT a FROM Author a ORDER BY a.authorRating DESC, a.name ASC")
    List<Author> findTopRatedAuthors();
    
    @Query("SELECT a FROM Author a ORDER BY a.authorRating DESC, a.name ASC")
    Page<Author> findTopRatedAuthors(Pageable pageable);
    
    @Query("SELECT a FROM Author a WHERE a.authorRating >= :minRating ORDER BY a.authorRating DESC, a.name ASC")
    List<Author> findAuthorsByMinimumRating(@Param("minRating") Integer minRating);
    
    @Query("SELECT a FROM Author a JOIN a.stories s GROUP BY a.id ORDER BY COUNT(s) DESC")
    List<Author> findMostProlificAuthors();
    
    @Query("SELECT a FROM Author a JOIN a.stories s GROUP BY a.id ORDER BY COUNT(s) DESC")
    Page<Author> findMostProlificAuthors(Pageable pageable);
    
    @Query("SELECT DISTINCT a FROM Author a JOIN a.urls u WHERE u LIKE %:domain%")
    List<Author> findByUrlDomain(@Param("domain") String domain);
    
    @Query("SELECT COUNT(a) FROM Author a WHERE a.createdAt >= :cutoffDate")
    long countRecentAuthors(@Param("cutoffDate") java.time.LocalDateTime cutoffDate);
    
    @Query(value = "SELECT author_rating FROM authors WHERE id = :id", nativeQuery = true)
    Integer findAuthorRatingById(@Param("id") UUID id);
    
}