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

namespace TeleWave.Application.Programming.Templates.Junctions;

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

        junction.Rename(command.Name);
        return await JunctionLoader.MarkTemplateChangedAsync(
            dbContext,
            junction,
            cancellationToken
        );
    }
}
