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

namespace TeleWave.Application.Programming.Templates.UpdateSlot;

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

        var applied = await writer.ApplyAsync(layer, slot, command.Input, cancellationToken);
        if (!applied.IsSuccess)
            return applied;

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