package com.test.musichouduan.repository;

import com.test.musichouduan.entity.Singer;
import com.test.musichouduan.entity.User;
import com.test.musichouduan.entity.UserSinger;
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;

/**
 * 用户歌手关联数据访问层
 */
@Repository
public interface UserSingerRepository extends JpaRepository<UserSinger, Long> {

    /**
     * 判断用户是否已收藏歌手
     *
     * @param user 用户
     * @param singer 歌手
     * @return 是否已收藏
     */
    boolean existsByUserAndSinger(User user, Singer singer);

    /**
     * 统计收藏指定歌手的用户数量
     *
     * @param singerId 歌手ID
     * @return 粉丝数量
     */
    Long countBySingerId(Long singerId);


    /**
     * 判断用户是否已收藏歌手
     *
     * @param userId 用户ID
     * @param singerId 歌手ID
     * @return 是否已收藏
     */
    boolean existsByUserIdAndSingerId(Long userId, Long singerId);

    /**
     * 收藏歌手
     *
     * @param userId 用户ID
     * @param singerId 歌手ID
     */
    @Modifying
    @Transactional
    @Query(value = "INSERT INTO user_singer (user_id, singer_id, collect_time) VALUES (?1, ?2, NOW())", nativeQuery = true)
    void collectSinger(Long userId, Long singerId);

    /**
     * 取消收藏歌手
     *
     * @param userId 用户ID
     * @param singerId 歌手ID
     */
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM user_singer WHERE user_id = ?1 AND singer_id = ?2", nativeQuery = true)
    void uncollectSinger(Long userId, Long singerId);

    /**
     * 获取用户收藏的歌手
     *
     * @param userId 用户ID
     * @param pageable 分页
     * @return 歌手分页
     */
    @Query("SELECT us.singer FROM UserSinger us WHERE us.user.id = ?1")
    Page<Singer> findCollectedSinger(Long userId, Pageable pageable);
}
