using CH.CQRS.Service.Energy; using CH.CQRS.Service.Energy.Options; using CH.Dal; using CH.Dal.DbEntity; using CH.Dal.Validators; using FluentValidation; using Microsoft.EntityFrameworkCore; using OpenHarbor.CQRS.Abstractions; namespace CH.CQRS.Command.Energy; public class UpdateEnergyProviderCommand { public long ProviderId { get; set; } public required string Name { get; set; } } public class UpdateEnergyProviderCommandHandler(EnergyService energyService) : ICommandHandler { public Task HandleAsync(UpdateEnergyProviderCommand command, CancellationToken cancellationToken = new CancellationToken()) { return energyService.UpdateEnergyProviderAsync(new UpdateEnergyProviderCommandOptions { ProviderId = command.ProviderId, Name = command.Name },cancellationToken); } } public class UpdateEnergyProviderCommandValidator : AbstractValidator { public UpdateEnergyProviderCommandValidator(CHDbContext dbContext) { RuleFor(command => command.Name) .NotEmpty() .MinimumLength(3) .MustAsync(async (name, cancellationToken) => { var nameInUse = await dbContext.EnergyProviders.AnyAsync(energyProvider => energyProvider.Name == name, cancellationToken); return false == nameInUse; }) .WithMessage("This Name is already in use by another energy provider."); RuleFor(command => command.ProviderId) .NotEmpty() .SetValidator(new DbEntityExistValidator(dbContext)); } }