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

namespace TeleWave.Application.Programming.Templates.CreateSlot;

public sealed class CreateSlotCommandHandler(SlotWriter writer)
    : ICommandHandler<CreateSlotCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(
        CreateSlotCommand command,
        CancellationToken cancellationToken
    )
    {
        var template = await writer.LoadTemplateByLayerAsync(command.LayerId, cancellationToken);
        var layer = template?.FindLayer(command.LayerId);
        if (template is null || layer is null)
            return Result.Failure<Guid>(TemplateErrors.LayerNotFound);

        var before = layer.Slots.Select(s => s.Id).ToHashSet();

        var applied = await writer.ApplyAsync(layer, null, command.Input, cancellationToken);
        if (!applied.IsSuccess)
            return Result.Failure<Guid>(applied.Error);

        // Правка правил эфир не двигает — только помечает шаблон изменённым (см. применение по кнопке).
        template.MarkChanged();

        var created = layer.Slots.First(s => !before.Contains(s.Id));
        return Result.Success(created.Id);
    }
}
