using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.Filler;

public class DeleteFillerPresetHandler : IRequestHandler<DeleteFillerPreset, Either<BaseError, Unit>>
{
    private readonly IDbContextFactory<TvContext> _dbContextFactory;

    public DeleteFillerPresetHandler(IDbContextFactory<TvContext> dbContextFactory) =>
        _dbContextFactory = dbContextFactory;

    public async Task<Either<BaseError, Unit>> Handle(
        DeleteFillerPreset request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
        Option<FillerPreset> maybeFillerPreset = await FillerPresetMustExist(dbContext, request, cancellationToken);

        // must-exist maps to a NotFoundError Either directly (not via Validation, which
        // aggregates errors and loses the subtype the API layer maps to 404)
        return await maybeFillerPreset.Match(
            Some: fillerPreset => DoDeletion(dbContext, fillerPreset).Map(Right<BaseError, Unit>),
            None: () => Task.FromResult<Either<BaseError, Unit>>(
                new NotFoundError($"FillerPreset {request.FillerPresetId} does not exist.")));
    }

    private static Task<Unit> DoDeletion(TvContext dbContext, FillerPreset fillerPreset)
    {
        dbContext.FillerPresets.Remove(fillerPreset);
        return dbContext.SaveChangesAsync().ToUnit();
    }

    private static Task<Option<FillerPreset>> FillerPresetMustExist(
        TvContext dbContext,
        DeleteFillerPreset request,
        CancellationToken cancellationToken) =>
        dbContext.FillerPresets
            .SelectOneAsync(fp => fp.Id, ps => ps.Id == request.FillerPresetId, cancellationToken);
}
