package com.example.backend.books.repository;

import java.util.List;

import org.springframework.data.domain.Limit;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.example.backend.books.model.BookEntity;

public interface BookRepository extends CrudRepository<BookEntity, Long>, PagingAndSortingRepository<BookEntity, Long> {
    List<BookEntity> findByCategoryId(long categoryId);

    List<BookEntity> findByIdIn(List<Long> ids);

    Page<BookEntity> findByCategoryId(long categoryId, Pageable pageable);

    @Query("SELECT b FROM BookEntity b WHERE (:categoryId IS NULL OR b.category.id = :categoryId) " +
            "AND ((:searchInfo IS NULL OR LOWER(b.title) LIKE %:searchInfo%) " +
            "OR (:searchInfo IS NULL OR LOWER(b.author) LIKE %:searchInfo%))")
    Page<BookEntity> findAllByFilters(@Param("categoryId") Long categoryId,
            @Param("searchInfo") String searchInfo,
            Pageable pageable);

    @Query("SELECT b FROM BookEntity b ORDER BY b.date desc")
    List<BookEntity> findSomeNewest(Limit limit);
}
