package com.yaoyuan.jiscuss.repository;

import com.yaoyuan.jiscuss.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface UsersRepository extends JpaRepository<User, Integer> {
    /**
     * @param username
     * @return
     */
    @Query("from User where username like %:username%")
    List<User> getByUsernameIsLike(@Param("username") String username);

    /**
     * @param id
     * @return
     */
    User getById(Integer id);

    /**
     * @param username
     * @return
     */
    @Query("from User where username = :username")
    User getByUsername(String username);

    // REMOVED: checkByUsernameAndPassword — never compare passwords at the SQL layer.
    // Password validation must go through BCryptPasswordEncoder.matches() in the service/security layer.

    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.commentsCount = COALESCE(u.commentsCount, 0) + 1 WHERE u.id = :id")
    void incrementCommentCount(@Param("id") Integer id);

    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.discussionsCount = COALESCE(u.discussionsCount, 0) + 1 WHERE u.id = :id")
    void incrementDiscussionCount(@Param("id") Integer id);

    /** Top active users by comment count (for the ranking sidebar). Shows all users if counts are 0. */
    @Query("FROM User u ORDER BY COALESCE(u.commentsCount, 0) DESC")
    List<User> findTop10ActiveUsers(org.springframework.data.domain.Pageable pageable);
}
