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);

        junction.Reorder(command.ElementIdsInOrder);
        return await JunctionLoader.MarkTemplateChangedAsync(
            dbContext,
            junction,
            cancellationToken
        );
    }
}
