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