package com.izouma.jmrh.repo;

import com.izouma.jmrh.domain.Post;
import com.izouma.jmrh.dto.MyPostAndComment;
import com.izouma.jmrh.dto.PostDTO;
import com.izouma.jmrh.enums.PostType;
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.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.annotation.Nonnull;
import javax.transaction.Transactional;
import java.util.List;

public interface PostRepo extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {

    @Query("update Post p set p.del = true where p.id = ?1")
    @Transactional
    @Modifying
    void deleteById(@Nonnull Long id);

    @Query("select p, u.nickname, u.avatar from Post p left join User u on p.userId = u.id where p.del = false")
    Page<PostDTO> allDTO(PostType type, Pageable pageable);

    @Query("select new com.izouma.jmrh.dto.MyPostAndComment(p, c, c.createdAt) from Comment c " +
            "join Post p on c.postId = p.id " +
            "where (c.userId = ?1 and c.del = false) and p.type = ?2 " +
            "order by c.createdAt desc")
    List<MyPostAndComment> myComment(Long userId, PostType type);

    @Query("select new com.izouma.jmrh.dto.MyPostAndComment(p, c, c.createdAt) from Post p " +
            "join Comment c on c.postId = p.id " +
            "where p.userId = ?1 and p.type = com.izouma.jmrh.enums.PostType.OFFICIAL and p.del = false " +
            "order by p.createdAt desc, c.createdAt desc")
    List<MyPostAndComment> myOfficial(Long userId);

    List<Post> findByUserIdAndTypeAndDelFalse(Long userId, PostType type);
}