using Ardalis.Result; using DispatchR.Abstractions.Send; using Microsoft.Extensions.Logging; using Musify.Application.Configuration; using Musify.Application.Contracts.Infrastructure; using Musify.Application.Events; using Musify.Application.PlayLists.Commands; namespace Musify.Application.PlayLists.Handlers { public class DeletePlayListCommandHandler(IDatabase database, IEventBus eventBus, ApplicationStorageConfiguration storageConfiguration, PlayListConfiguration playListConfiguration, ILogger logger) : IRequestHandler> { public async Task Handle(DeletePlayListCommand request, CancellationToken cancellationToken) { var playList = await database.PlayLists.FindAsync(request.PlayListId, cancellationToken); if (playList is null) { logger.LogDebug("PlayList with id={PlayListId} not found", request.PlayListId); return Result.NotFound(); } if (playList.UserId != request.UserId) { logger.LogInformation("PlayList with id={PlayListId} does not belong to user with id={UserId}", request.PlayListId, request.UserId); return Result.Unauthorized(); } var keysToRemove = new List(); if (playList.SmallPictureKeyName != playListConfiguration.Routes.PresetSmallPicture) keysToRemove.Add(Path.Combine( playListConfiguration.Routes.ParentFolders, playListConfiguration.Routes.SmallPictures, playList.SmallPictureKeyName)); if (playList.MediumPictureKeyName != playListConfiguration.Routes.PresetMediumPicture) keysToRemove.Add(Path.Combine( playListConfiguration.Routes.ParentFolders, playListConfiguration.Routes.MediumPictures, playList.MediumPictureKeyName)); if (playList.LargePictureKeyName != playListConfiguration.Routes.PresetLargePicture) keysToRemove.Add(Path.Combine( playListConfiguration.Routes.ParentFolders, playListConfiguration.Routes.LargePictures, playList.LargePictureKeyName)); foreach (var key in keysToRemove) { var publishResult = await TryPublishRemoveFileEventAsync(playList.Id, key, cancellationToken); if (!publishResult.IsSuccess) { if (publishResult.IsNotFound()) { logger.LogWarning("File with key={KeyName} not found in storage while trying to publish remove file event for PlayList with id={PlayListId}.", key, playList.Id); continue; } return publishResult; } } database.PlayLists.Remove(playList); await database.SaveChangesAsync(cancellationToken); return Result.NoContent(); } async Task TryPublishRemoveFileEventAsync(Guid playListId, string keyName, CancellationToken cancellationToken) { try { await eventBus.PublishAsync(new RemoveFileEvent( storageConfiguration.BucketName, keyName), cancellationToken); return Result.Success(); } catch (Exception exception) { logger.LogError(exception, "Failed to publish remove file event for PlayList id={PlayListId} and key={KeyName}.", playListId, keyName); return Result.Error($"Failed to publish remove file event for PlayList with id {playListId}."); } } } }