package org.codiki.core.repositories;

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

import org.codiki.core.entities.persistence.Post;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface PostRepository extends CrudRepository<Post, Long>, PostSearchRepository {

	@Query("SELECT p FROM Post p WHERE p.key = :postKey")
	Optional<Post> getByKey(@Param("postKey") final String pPostKey);
	
	// TODO : Remove "JOIN FETCH u.role", actually necessary for JSON serialization
	@Query("SELECT p FROM Post p JOIN FETCH p.author u JOIN FETCH u.role ORDER BY p.creationDate DESC")
	List<Post> getLast(Pageable pPageable);
	
	@Query(value = "SELECT * FROM post p INNER JOIN \"user\" u ON u.id = creator_id WHERE category_id = :categoryId ORDER BY creation_date DESC",
			nativeQuery = true)
	List<Post> getByCategoryId(@Param("categoryId") final Long pCategoryId);
	
	@Query(value = "SELECT * FROM post WHERE creator_id = :creatorId ORDER BY creation_date DESC",
			nativeQuery = true)
	List<Post> getByCreator(@Param("creatorId") final Long pCreatorId);
	
	@Query(value = "SELECT * FROM Post WHERE id = :id", nativeQuery = true)
	Optional<Post> getOne(@Param("id") final Long id);
}
