using System.Threading.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.Playouts;

public class ResetAllPlayoutsHandler(
    IEntityLocker locker,
    ChannelWriter<IBackgroundServiceRequest> channel,
    IDbContextFactory<TvContext> dbContextFactory)
    : IRequestHandler<ResetAllPlayouts, ResetAllPlayoutsResult>
{
    public async Task<ResetAllPlayoutsResult> Handle(
        ResetAllPlayouts request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);

        var queued = new List<int>();
        var skippedLocked = new List<int>();
        var skippedUnsupported = new List<int>();

        foreach (Playout playout in await dbContext.Playouts.ToListAsync(cancellationToken))
        {
            switch (playout.ScheduleKind)
            {
                case PlayoutScheduleKind.Classic:
                    if (locker.IsPlayoutLocked(playout.Id))
                    {
                        skippedLocked.Add(playout.Id);
                    }
                    else
                    {
                        await channel.WriteAsync(
                            new BuildPlayout(playout.Id, PlayoutBuildMode.Refresh),
                            cancellationToken);
                        queued.Add(playout.Id);
                    }

                    break;
                case PlayoutScheduleKind.Block:
                case PlayoutScheduleKind.Sequential:
                case PlayoutScheduleKind.Scripted:
                    if (locker.IsPlayoutLocked(playout.Id))
                    {
                        skippedLocked.Add(playout.Id);
                    }
                    else
                    {
                        await channel.WriteAsync(
                            new BuildPlayout(playout.Id, PlayoutBuildMode.Reset),
                            cancellationToken);
                        queued.Add(playout.Id);
                    }

                    break;
                case PlayoutScheduleKind.ExternalJson:
                case PlayoutScheduleKind.None:
                default:
                    // external json cannot be reset
                    skippedUnsupported.Add(playout.Id);
                    continue;
            }
        }

        return new ResetAllPlayoutsResult(queued, skippedLocked, skippedUnsupported);
    }
}
