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

namespace TeleWave.Application.Programming.Templates.Junctions;

public sealed class RemoveJunctionElementCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<RemoveJunctionElementCommand, Result>
{
    public async Task<Result> Handle(
        RemoveJunctionElementCommand command,
        CancellationToken cancellationToken
    )
    {
        var junction = await JunctionLoader.LoadAsync(
            dbContext,
            command.JunctionId,
            cancellationToken
        );
        if (junction is null || !junction.RemoveElement(command.ElementId))
            return Result.Failure(TemplateErrors.JunctionElementNotFound);

        return await JunctionLoader.MarkTemplatesChangedAsync(
            dbContext,
            junction.Id,
            cancellationToken
        );
    }
}
