using System.Threading.Channels; using ErsatzTV.Core; using ErsatzTV.Core.Errors; using ErsatzTV.Core.Interfaces.Search; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using static ErsatzTV.Application.Channels.ChannelValidations; using Channel = ErsatzTV.Core.Domain.Channel; namespace ErsatzTV.Application.Channels; public class BulkMoveChannelsToGroupHandler( IDbContextFactory dbContextFactory, ChannelWriter workerChannel, ISearchTargets searchTargets) : IRequestHandler> { public async Task> Handle( BulkMoveChannelsToGroup request, CancellationToken cancellationToken) { if (request.ChannelIds.Count == 0) { return Left(BaseError.New("At least one channel id is required")); } Validation groupValidation = ValidateGroup(request.Group); if (groupValidation.IsFail) { return Left(groupValidation.FailToSeq().Head()); } await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken); List channelIds = request.ChannelIds.Distinct().ToList(); List channels = await dbContext.Channels .Where(c => channelIds.Contains(c.Id)) .ToListAsync(cancellationToken); if (channels.Count != channelIds.Count) { var found = channels.Select(c => c.Id).ToHashSet(); int missingId = channelIds.First(id => !found.Contains(id)); return Left(new NotFoundError($"Channel {missingId} does not exist.")); } foreach (Channel channel in channels) { channel.Group = request.Group; } await dbContext.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); searchTargets.SearchTargetsChanged(); // post-commit side effect runs on CancellationToken.None so a late request cancellation // can't abort it after the commit landed (#254) await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None); return Right(Unit.Default); } }