package app.mealsmadeeasy.api.image;

import app.mealsmadeeasy.api.user.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.Optional;

public interface ImageRepository extends JpaRepository<Image, Integer> {

    @Query("SELECT image FROM Image image WHERE image.id = ?1")
    @EntityGraph(attributePaths = { "viewers" })
    Image getByIdWithViewers(Integer id);

    List<Image> findAllByOwner(User owner);
    Optional<Image> findByOwnerAndUserFilename(User owner, String filename);

    @Query("SELECT image from Image image WHERE image.owner.username = ?1 AND image.userFilename = ?2")
    Optional<Image> findByOwnerUsernameAndFilename(String username, String filename);

    @Query("SELECT i FROM Image i WHERE i.owner = ?1")
    Slice<Image> findAllOwnedBy(User user, Pageable pageable);

    int countAllByOwner(User owner);

}
