package com.vibevault.controller;

import java.security.Principal;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.vibevault.dto.CopyPlaylistRequest;
import com.vibevault.dto.PlaylistCreateDTO;
import com.vibevault.dto.PlaylistDTO;
import com.vibevault.dto.SongCreateDTO;
import com.vibevault.service.PlaylistService;

/**
 * 歌单 REST 控制器
 * 
 * 需要实现以下端点：
 * - GET /api/playlists - 获取所有歌单（公开）
 * - GET /api/playlists/{id} - 获取指定歌单（公开）
 * - POST /api/playlists - 创建歌单（需认证）
 * - POST /api/playlists/{id}/songs - 添加歌曲（需认证）
 * - DELETE /api/playlists/{playlistId}/songs/{songId} - 移除歌曲（需认证）
 * - DELETE /api/playlists/{id} - 删除歌单（需认证）
 * 
 * [Advanced] 额外端点：
 * - GET /api/playlists/search?keyword=xxx - 搜索歌单
 * - POST /api/playlists/{id}/copy?newName=xxx - 复制歌单
 * 
 * 提示：
 * - 使用 Authentication 参数获取当前用户名：authentication.getName()
 * - 使用 @ResponseStatus 设置正确的 HTTP 状态码
 */
@RestController
@RequestMapping("/api/playlists")
public class PlaylistController {

    private final PlaylistService playlistService;

    public PlaylistController(PlaylistService playlistService) {
        this.playlistService = playlistService;
    }

    // GET /api/playlists - 获取所有歌单（公开）
    @GetMapping
    public List<PlaylistDTO> getAllPlaylists() {
        return playlistService.getAllPlaylists();
    }

    // GET /api/playlists/{id} - 获取指定歌单（公开）
    @GetMapping("/{id}")
    public PlaylistDTO getPlaylistById(@PathVariable Long id) {
        return playlistService.getPlaylistById(id);
    }

    // POST /api/playlists - 创建歌单（需认证）
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public PlaylistDTO createPlaylist(@RequestBody PlaylistCreateDTO playlistCreateDTO, Authentication authentication) {
        String username = authentication.getName();
        return playlistService.createPlaylist(playlistCreateDTO.name(), username);
    }

    // POST /api/playlists/{id}/songs - 添加歌曲（需认证）
    @PostMapping("/{id}/songs")
    @ResponseStatus(HttpStatus.CREATED)
    public PlaylistDTO addSongToPlaylist(@PathVariable Long id, @RequestBody SongCreateDTO songCreateDTO, Authentication authentication) {
        String username = authentication.getName();
        return playlistService.addSongToPlaylist(id, songCreateDTO, username);
    }

    // POST /api/playlists/{id}/songs/batch - 批量添加歌曲（需认证）
    @PostMapping("/{id}/songs/batch")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<PlaylistDTO> addSongsToPlaylist(@PathVariable Long id, @RequestBody List<SongCreateDTO> songs, Principal principal) {
        PlaylistDTO updatedPlaylist = playlistService.addSongsToPlaylist(id, songs, principal.getName());
        return ResponseEntity.ok(updatedPlaylist);
    }
    
    /**
     * [Advanced] 复制歌单
     * 
     * @param id 要复制的歌单ID
     * @param request 复制请求（包含新歌单名称）
     * @param principal 当前用户
     * @return 新创建的歌单DTO
     */
    @PostMapping("/{id}/copy")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<PlaylistDTO> copyPlaylist(@PathVariable Long id, @RequestBody CopyPlaylistRequest request, Principal principal) {
        PlaylistDTO copiedPlaylist = playlistService.copyPlaylist(id, request.getNewName(), principal.getName());
        return ResponseEntity.status(HttpStatus.CREATED).body(copiedPlaylist);
    }
    
    /**
     * [Advanced] 按条件筛选歌单
     * 
     * @param ownerName 歌单拥有者名称（可选）
     * @param nameKeyword 歌单名称关键词（可选）
     * @param sortBy 排序字段（name或createdAt）
     * @param sortDirection 排序方向（asc或desc）
     * @param principal 当前用户
     * @return 筛选后的歌单列表
     */
    @GetMapping("/filter")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<List<PlaylistDTO>> filterPlaylists(
            @RequestParam(required = false) String ownerName,
            @RequestParam(required = false) String nameKeyword,
            @RequestParam(required = false, defaultValue = "name") String sortBy,
            @RequestParam(required = false, defaultValue = "asc") String sortDirection,
            Principal principal) {
        List<PlaylistDTO> filteredPlaylists = playlistService.filterPlaylists(
                principal.getName(), ownerName, nameKeyword, sortBy, sortDirection);
        return ResponseEntity.ok(filteredPlaylists);
    }

    // DELETE /api/playlists/{playlistId}/songs/{songId} - 移除歌曲（需认证）
    @DeleteMapping("/{playlistId}/songs/{songId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void removeSongFromPlaylist(@PathVariable Long playlistId, @PathVariable Long songId, Authentication authentication) {
        String username = authentication.getName();
        playlistService.removeSongFromPlaylist(playlistId, songId, username);
    }

    // DELETE /api/playlists/{id} - 删除歌单（需认证）
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deletePlaylist(@PathVariable Long id, Authentication authentication) {
        String username = authentication.getName();
        playlistService.deletePlaylist(id, username);
    }

    // [Advanced] GET /api/playlists/search?keyword=xxx - 搜索歌单
    @GetMapping("/search")
    public List<PlaylistDTO> searchPlaylists(@RequestParam String keyword) {
        return playlistService.searchPlaylists(keyword);
    }


}
