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

namespace TeleWave.Application.Programming.Templates.Junctions;

public sealed class AddJunctionElementCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<AddJunctionElementCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(
        AddJunctionElementCommand command,
        CancellationToken cancellationToken
    )
    {
        var junction = await JunctionLoader.LoadAsync(
            dbContext,
            command.JunctionId,
            cancellationToken
        );
        if (junction is null)
            return Result.Failure<Guid>(TemplateErrors.JunctionNotFound);

        var element = junction.AddElement(command.Kind);
        await JunctionLoader.MarkTemplatesChangedAsync(dbContext, junction.Id, cancellationToken);
        return Result.Success(element.Id);
    }
}
