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