using Indotalent.ConfigBackEnd.Exceptions; using Indotalent.ConfigBackEnd.Extensions; using Indotalent.Infrastructure.Database; using MediatR; using Microsoft.EntityFrameworkCore; namespace Indotalent.Features.Thirdparty.CustomerGroup.Cqrs; public class CreateCustomerGroupRequest { public string? Name { get; set; } public string? Description { get; set; } } public class CreateCustomerGroupResponse { public string? Id { get; set; } public string? Name { get; set; } } public record CreateCustomerGroupCommand(CreateCustomerGroupRequest Data) : IRequest; public class CreateCustomerGroupHandler : IRequestHandler { private readonly AppDbContext _context; public CreateCustomerGroupHandler(AppDbContext context) => _context = context; public async Task Handle(CreateCustomerGroupCommand request, CancellationToken cancellationToken) { var isExists = await _context.CustomerGroup .AnyAsync(x => x.Name == request.Data.Name, cancellationToken); if (isExists) { throw new AlreadyExistsException("Customer Group", request.Data.Name ?? string.Empty); } var entity = new Data.Entities.CustomerGroup { Name = request.Data.Name, Description = request.Data.Description }; _context.CustomerGroup.Add(entity); await _context.SaveChangesAsync(cancellationToken); return new CreateCustomerGroupResponse { Id = entity.Id, Name = entity.Name }; } }