// Controllers/TrackController.cs
using Microsoft.AspNetCore.Mvc;

namespace PlaylistShared.Controllers;

[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/tracks")]
[Authorize]
public class TrackController : ControllerBase
{
    private readonly AppDbContext _db;
    private readonly IYandexMusicService _yandex;

    public TrackController(AppDbContext db, IYandexMusicService yandex)
    {
        _db = db;
        _yandex = yandex;
    }

    [HttpPost("add")]
    public async Task<IActionResult> AddTrack(Guid playlistId, string trackId, string? trackTitle, string? artist)
    {
        var playlist = await _db.SharedPlaylists
            .Include(p => p.Owner)
            .FirstOrDefaultAsync(p => p.Id == playlistId);
        if (playlist == null) return NotFound();

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (!CanAdd(playlist, userId)) return Forbid();

        // Добавляем в Яндекс
        await _yandex.AddTrackToPlaylistAsync(playlist.OwnerUserId, playlist.YandexPlaylistId, trackId);

        // Сохраняем информацию о треке в кеш
        var track = new PlaylistTrack
        {
            Id = Guid.NewGuid(),
            PlaylistId = playlist.Id,
            YandexTrackId = trackId,
            Title = trackTitle ?? "Unknown",
            Artist = artist,
            AddedByUserId = userId,
            AddedAt = DateTime.UtcNow
        };
        _db.PlaylistTracks.Add(track);
        await _db.SaveChangesAsync();
        return Ok();
    }

    [HttpDelete("remove")]
    public async Task<IActionResult> RemoveTrack(Guid playlistId, string trackId)
    {
        var playlist = await _db.SharedPlaylists
            .Include(p => p.Owner)
            .FirstOrDefaultAsync(p => p.Id == playlistId);
        if (playlist == null) return NotFound();

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        var trackEntry = await _db.PlaylistTracks
            .FirstOrDefaultAsync(t => t.PlaylistId == playlistId && t.YandexTrackId == trackId);
        if (!CanDelete(playlist, userId, trackEntry?.AddedByUserId))
            return Forbid();

        await _yandex.RemoveTrackFromPlaylistAsync(playlist.OwnerUserId, playlist.YandexPlaylistId, trackId);
        if (trackEntry != null) _db.PlaylistTracks.Remove(trackEntry);
        await _db.SaveChangesAsync();
        return Ok();
    }

    private bool CanAdd(SharedPlaylist playlist, string? userId)
    {
        return playlist.Permissions.Add switch
        {
            AccessLevel.All => true,
            AccessLevel.Authorized => userId != null,
            AccessLevel.None => false,
            _ => false
        };
    }

    private bool CanDelete(SharedPlaylist playlist, string? userId, string? adderUserId)
    {
        if (userId == playlist.OwnerUserId) return true; // владелец всегда может удалить
        return playlist.Permissions.Delete switch
        {
            DeleteAccessLevel.All => true,
            DeleteAccessLevel.Authorized => userId != null,
            DeleteAccessLevel.AdderOnly => userId != null && userId == adderUserId,
            DeleteAccessLevel.OwnerOnly => false,
            _ => false
        };
    }
}