using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Application.Search;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.MediaCollections;

public class AddMediaItemToCollectionHandler :
    IRequestHandler<AddMediaItemToCollection, Either<BaseError, Unit>>
{
    private readonly ChannelWriter<IBackgroundServiceRequest> _channel;
    private readonly IDbContextFactory<TvContext> _dbContextFactory;
    private readonly IMediaCollectionRepository _mediaCollectionRepository;
    private readonly ChannelWriter<ISearchIndexBackgroundServiceRequest> _searchChannel;

    public AddMediaItemToCollectionHandler(
        IDbContextFactory<TvContext> dbContextFactory,
        IMediaCollectionRepository mediaCollectionRepository,
        ChannelWriter<IBackgroundServiceRequest> channel,
        ChannelWriter<ISearchIndexBackgroundServiceRequest> searchChannel)
    {
        _dbContextFactory = dbContextFactory;
        _mediaCollectionRepository = mediaCollectionRepository;
        _channel = channel;
        _searchChannel = searchChannel;
    }

    public async Task<Either<BaseError, Unit>> Handle(
        AddMediaItemToCollection request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
        Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
        return await validation.Apply(parameters => ApplyAddMediaItemRequest(dbContext, parameters));
    }

    private async Task<Unit> ApplyAddMediaItemRequest(TvContext dbContext, Parameters parameters)
    {
        parameters.Collection.MediaItems.Add(parameters.MediaItem);
        if (await dbContext.SaveChangesAsync() > 0)
        {
            await _searchChannel.WriteAsync(new ReindexMediaItems([parameters.MediaItem.Id]));

            // refresh all playouts that use this collection
            foreach (int playoutId in await _mediaCollectionRepository
                         .PlayoutIdsUsingCollection(parameters.Collection.Id))
            {
                await _channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh));
            }
        }

        return Unit.Default;
    }

    private static async Task<Validation<BaseError, Parameters>> Validate(
        TvContext dbContext,
        AddMediaItemToCollection request,
        CancellationToken cancellationToken) =>
        (await CollectionMustExist(dbContext, request, cancellationToken),
            await ValidateMediaItem(dbContext, request, cancellationToken))
        .Apply((collection, episode) => new Parameters(collection, episode));

    private static Task<Validation<BaseError, Collection>> CollectionMustExist(
        TvContext dbContext,
        AddMediaItemToCollection request,
        CancellationToken cancellationToken) =>
        dbContext.Collections
            .Include(c => c.MediaItems)
            .SelectOneAsync(c => c.Id, c => c.Id == request.CollectionId, cancellationToken)
            .Map(o => o.ToValidation<BaseError>("Collection does not exist."));

    private static Task<Validation<BaseError, MediaItem>> ValidateMediaItem(
        TvContext dbContext,
        AddMediaItemToCollection request,
        CancellationToken cancellationToken) =>
        dbContext.MediaItems
            .SelectOneAsync(m => m.Id, e => e.Id == request.MediaItemId, cancellationToken)
            .Map(o => o.ToValidation<BaseError>("MediaItem does not exist"));

    private sealed record Parameters(Collection Collection, MediaItem MediaItem);
}
