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

namespace TeleWave.Application.Programming.Templates.Junctions;

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

        junction.Update(command.Name, command.MaxTotalSeconds);
        return await JunctionLoader.MarkTemplatesChangedAsync(
            dbContext,
            junction.Id,
            cancellationToken
        );
    }
}
