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

namespace TeleWave.Application.Programming.Templates.Junctions;

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

        // Порядок и принадлежность к развилке приезжают вместе: в цепочке это один жест мышью.
        foreach (var position in command.Order)
            if (junction.FindElement(position.ElementId) is { } element)
                element.SetChoice(position.ChoiceKey, element.ChoiceWeight);

        junction.Reorder(command.Order.Select(o => o.ElementId));
        return await JunctionLoader.MarkTemplatesChangedAsync(
            dbContext,
            junction.Id,
            cancellationToken
        );
    }
}
