package com.test.musichouduan.repository;

import com.test.musichouduan.entity.Playlist;
import com.test.musichouduan.entity.User;
import com.test.musichouduan.entity.UserPlaylist;
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 UserPlaylistRepository extends JpaRepository<UserPlaylist, Long> {

    /**
     * 判断用户是否已收藏歌单
     *
     * @param user 用户
     * @param playlist 歌单
     * @return 是否已收藏
     */
    boolean existsByUserAndPlaylist(User user, Playlist playlist);

    /**
     * 判断用户是否已收藏歌单
     *
     * @param userId 用户ID
     * @param playlistId 歌单ID
     * @return 是否已收藏
     */
    boolean existsByUserIdAndPlaylistId(Long userId, Long playlistId);

    /**
     * 收藏歌单
     *
     * @param userId 用户ID
     * @param playlistId 歌单ID
     */
    @Modifying
    @Transactional
    @Query(value = "INSERT INTO user_playlist (user_id, playlist_id, collect_time) VALUES (?1, ?2, NOW())", nativeQuery = true)
    void collectPlaylist(Long userId, Long playlistId);

    /**
     * 取消收藏歌单
     *
     * @param userId 用户ID
     * @param playlistId 歌单ID
     */
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM user_playlist WHERE user_id = ?1 AND playlist_id = ?2", nativeQuery = true)
    void uncollectPlaylist(Long userId, Long playlistId);

    /**
     * 获取用户收藏的歌单
     *
     * @param userId 用户ID
     * @param pageable 分页
     * @return 歌单分页
     */
    @Query("SELECT up.playlist FROM UserPlaylist up WHERE up.user.id = ?1")
    Page<Playlist> findCollectedPlaylist(Long userId, Pageable pageable);
}
