using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Broadcast.Bumpers;

public sealed class RemoveBumperTemplateCommandHandler(
    IAppDbContext dbContext,
    IBumperTemplateStorage storage
) : ICommandHandler<RemoveBumperTemplateCommand, Result>
{
    public async Task<Result> Handle(
        RemoveBumperTemplateCommand command,
        CancellationToken cancellationToken
    )
    {
        var channel = await dbContext
            .Channels.Include(c => c.BumperTemplates)
            .FirstOrDefaultAsync(c => c.Id == command.ChannelId, cancellationToken);
        if (channel is null)
            return Result.Failure(ChannelErrors.NotFound);

        var template = channel.FindBumperTemplate(command.TemplateId);
        if (template is null)
            return Result.Failure(ChannelErrors.BumperTemplateNotFound);
        if (template.IsDefault)
            return Result.Failure(ChannelErrors.CannotRemoveDefaultBumperTemplate);

        channel.RemoveBumperTemplate(command.TemplateId);
        await dbContext.SaveChangesAsync(cancellationToken);
        await storage.DeleteTemplateAsync(command.TemplateId, cancellationToken);
        return Result.Success();
    }
}
