package com.test.musichouduan.repository;

import com.test.musichouduan.entity.Music;
import com.test.musichouduan.entity.User;
import com.test.musichouduan.entity.UserMusic;
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 UserMusicRepository extends JpaRepository<UserMusic, Long> {

    /**
     * 判断用户是否已收藏音乐
     *
     * @param user 用户
     * @param music 音乐
     * @return 是否已收藏
     */
    boolean existsByUserAndMusic(User user, Music music);

    /**
     * 判断用户是否已收藏音乐
     *
     * @param userId 用户ID
     * @param musicId 音乐ID
     * @return 是否已收藏
     */
    boolean existsByUserIdAndMusicId(Long userId, Long musicId);

    /**
     * 收藏音乐
     *
     * @param userId 用户ID
     * @param musicId 音乐ID
     */
    @Modifying
    @Transactional
    @Query(value = "INSERT INTO user_music (user_id, music_id, collect_time) VALUES (?1, ?2, NOW())", nativeQuery = true)
    void collectMusic(Long userId, Long musicId);

    /**
     * 取消收藏音乐
     *
     * @param userId 用户ID
     * @param musicId 音乐ID
     */
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM user_music WHERE user_id = ?1 AND music_id = ?2", nativeQuery = true)
    void uncollectMusic(Long userId, Long musicId);

    /**
     * 获取用户收藏的音乐
     *
     * @param userId 用户ID
     * @param pageable 分页
     * @return 用户音乐关联分页
     */
    @Query("SELECT um FROM UserMusic um WHERE um.user.id = ?1")
    Page<UserMusic> findCollectedMusic(Long userId, Pageable pageable);
}
