using CandidateReviewContracts.BindingModels; using CandidateReviewContracts.SearchModels; using CandidateReviewContracts.StoragesContracts; using CandidateReviewContracts.ViewModels; using CandidateReviewDatabaseImplement.Models; using CandidateReviewDataModels.Enums; using Microsoft.EntityFrameworkCore; namespace CandidateReviewDatabaseImplement.Implements { public class UserStorage : IUserStorage { public UserViewModel? Delete(UserBindingModel model) { using var context = new CandidateReviewDatabase(); var element = context.Users.Include(x => x.Company).Include(x => x.Resumes).Include(x => x.Assessments).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Users.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public UserViewModel? GetElement(UserSearchModel model) { if (string.IsNullOrEmpty(model.Email) && !model.Id.HasValue) { return null; } using var context = new CandidateReviewDatabase(); return context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email) || (model.Id.HasValue && x.Id == model.Id))? .GetViewModel; } public List GetFilteredList(UserSearchModel model) { using var context = new CandidateReviewDatabase(); if (model.CompanyId.HasValue && model.Role != null) { return context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .Where(x => x.CompanyId.Equals(model.CompanyId) && x.Role.Equals(model.Role)) .Select(x => x.GetViewModel) .ToList(); } else if (string.IsNullOrEmpty(model.Email) || string.IsNullOrEmpty(model.Password)) { return new(); } return context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .Where(x => x.Email.Equals(model.Email) && x.Password.Equals(model.Password)) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new CandidateReviewDatabase(); return context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .ToList() .Select(x => x.GetViewModel) .ToList(); } public UserViewModel? Insert(UserBindingModel model) { var newUser = User.Create(model); if (newUser == null) { return null; } using var context = new CandidateReviewDatabase(); context.Users.Add(newUser); context.SaveChanges(); return context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .FirstOrDefault(x => x.Id == newUser.Id)? .GetViewModel; } public UserViewModel? Update(UserBindingModel model) { using var context = new CandidateReviewDatabase(); var user = context.Users .Include(x => x.Company) .Include(x => x.Resumes) .Include(x => x.Assessments) .FirstOrDefault(x => x.Id == model.Id); if (user == null) { return null; } user.Update(model); context.SaveChanges(); return user.GetViewModel; } } }