using LiteCqrs;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Programming.Templates.DeleteSlot;

public sealed class DeleteSlotCommandHandler(SlotWriter writer)
    : ICommandHandler<DeleteSlotCommand, Result>
{
    public async Task<Result> Handle(DeleteSlotCommand command, CancellationToken cancellationToken)
    {
        var template = await writer.LoadTemplateBySlotAsync(command.SlotId, cancellationToken);
        var layer = template?.FindLayerOfSlot(command.SlotId);
        if (template is null || layer is null || !layer.RemoveSlot(command.SlotId))
            return Result.Failure(TemplateErrors.SlotNotFound);

        template.MarkChanged();
        return Result.Success();
    }
}
