package com.yaoyuan.jiscuss.repository;

import com.yaoyuan.jiscuss.entity.Discussion;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Repository
public interface DiscussionsRepository extends JpaRepository<Discussion, Integer> {

    @Query(value = "SELECT * from discussion where id in (\n" +
            "SELECT discussion_id from discussiontag where tag_id = ?1 )  ", nativeQuery = true)
    Page<Discussion> findByQuery(String tagId, Pageable pageable);

    @Modifying
    @Transactional
    @Query("UPDATE Discussion d SET d.viewCount = d.viewCount + 1 WHERE d.id = :id")
    void incrementViewCount(@org.springframework.data.repository.query.Param("id") Integer id);

    @Modifying
    @Transactional
    @Query("UPDATE Discussion d SET d.commentsCount = COALESCE(d.commentsCount, 0) + 1, d.lastTime = :lastTime, d.lastUserId = :userId WHERE d.id = :id")
    void incrementCommentCount(
            @org.springframework.data.repository.query.Param("id") Integer id,
            @org.springframework.data.repository.query.Param("userId") Integer userId,
            @org.springframework.data.repository.query.Param("lastTime") Date lastTime);

    @Modifying
    @Transactional
    @Query("UPDATE Discussion d SET d.likeCount = COALESCE(d.likeCount, 0) + :delta WHERE d.id = :id")
    void adjustLikeCount(@org.springframework.data.repository.query.Param("id") Integer id,
                         @org.springframework.data.repository.query.Param("delta") int delta);

    @Modifying
    @Transactional
    @Query("UPDATE Discussion d SET d.dislikeCount = COALESCE(d.dislikeCount, 0) + :delta WHERE d.id = :id")
    void adjustDislikeCount(@org.springframework.data.repository.query.Param("id") Integer id,
                            @org.springframework.data.repository.query.Param("delta") int delta);

    /** Discussions started by a given user, most recent first. */
    @Query("SELECT d FROM Discussion d WHERE d.startUserId = :userId ORDER BY d.startTime DESC")
    org.springframework.data.domain.Page<Discussion> findByStartUserIdOrderByStartTimeDesc(
            @org.springframework.data.repository.query.Param("userId") Integer userId,
            org.springframework.data.domain.Pageable pageable);
    long countByStartUserId(Integer startUserId);
}
