using System.IO.Abstractions; using System.Threading.Channels; using ErsatzTV.Core; using ErsatzTV.Core.Errors; using ErsatzTV.Core.Interfaces.Search; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Channel = ErsatzTV.Core.Domain.Channel; namespace ErsatzTV.Application.Channels; public class BulkDeleteChannelsHandler( IDbContextFactory dbContextFactory, ChannelWriter workerChannel, IFileSystem fileSystem, ISearchTargets searchTargets) : IRequestHandler> { public async Task> Handle( BulkDeleteChannels request, CancellationToken cancellationToken) { if (request.ChannelIds.Count == 0) { return Left(BaseError.New("At least one channel id is required")); } 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.")); } dbContext.Channels.RemoveRange(channels); await dbContext.SaveChangesAsync(cancellationToken); // Clean up the system-owned weighted-auto-tune artifacts these channels created (#425), inside the // same transaction — see DeleteChannelHandler for the cascade rationale. await dbContext.MultiCollections .Where(mc => mc.OwnedByChannelId != null && channelIds.Contains(mc.OwnedByChannelId.Value)) .ExecuteDeleteAsync(cancellationToken); await dbContext.SmartCollections .Where(sc => sc.OwnedByChannelId != null && channelIds.Contains(sc.OwnedByChannelId.Value)) .ExecuteDeleteAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); searchTargets.SearchTargetsChanged(); foreach (Channel channel in channels) { string cacheFile = Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, $"{channel.Number}.xml"); if (fileSystem.File.Exists(cacheFile)) { fileSystem.File.Delete(cacheFile); } } // 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); } }