using AppContext.Entities; using Converters; using Microsoft.EntityFrameworkCore; using Model; using Services; using Services.Failures; namespace DbServices; public class DbUserService(AppContext.AppContext context) : UserService { public Task> ListUsers(string nameNeedle) { return Task.FromResult( context.Users .Where(n => n.Name.ToLower().Contains(nameNeedle.ToLower())) .AsEnumerable() .Select(e => e.ToModel()) ); } public Task> ListUsers() { return Task.FromResult( context.Users .AsEnumerable() .Select(e => e.ToModel()) ); } public async Task GetUser(int id) { return (await context.Users.FirstOrDefaultAsync(e => e.Id == id))?.ToModel(); } public async Task CreateUser(string username, string email, string password, string profilePicture, bool isAdmin) { var userEntity = new UserEntity { Name = username, Email = email, Password = password, ProfilePicture = profilePicture, IsAdmin = isAdmin }; await context.Users.AddAsync(userEntity); await context.SaveChangesAsync(); return userEntity.ToModel(); } public async Task RemoveUsers(params int[] identifiers) { return await context.Users.Where(u => identifiers.Contains(u.Id)).ExecuteDeleteAsync() > 0; } public async Task UpdateUser(User user) { var entity = await context.Users.FirstOrDefaultAsync(e => e.Id == user.Id); if (entity == null) throw new ServiceException(Failure.NotFound("User not found")); entity.ProfilePicture = user.ProfilePicture; entity.Name = user.Name; entity.Email = user.Email; entity.Id = user.Id; await context.SaveChangesAsync(); } }