using AutoMapper; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading; using System.Threading.Tasks; using UserManagement.Common.UnitOfWork; using UserManagement.Data; using UserManagement.Data.Dto; using UserManagement.Domain; using UserManagement.Helper; using UserManagement.MediatR.Commands; using UserManagement.Repository; namespace UserManagement.MediatR.Handlers { public class AddEmailSMTPSettingCommandHandler( IEmailSMTPSettingRepository emailSMTPSettingRepository, IMapper mapper, IUnitOfWork uow ) : IRequestHandler> { public async Task> Handle(AddEmailSMTPSettingCommand request, CancellationToken cancellationToken) { var entity = mapper.Map(request); emailSMTPSettingRepository.Add(entity); // remove other as default if (entity.IsDefault) { var defaultEmailSMTPSettings = await emailSMTPSettingRepository.All .Where(c => c.IsDefault).ToListAsync(cancellationToken); defaultEmailSMTPSettings.ForEach(c => c.IsDefault = false); emailSMTPSettingRepository.UpdateRange(defaultEmailSMTPSettings); } else { var count = await emailSMTPSettingRepository.All.CountAsync(); if (count == 0) { entity.IsDefault = true; } } if (await uow.SaveAsync(cancellationToken) <= 0) { return ServiceResponse.Return500(); } var entityDto = mapper.Map(entity); return ServiceResponse.ReturnResultWith200(entityDto); } } }