using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.EntityFrameworkCore; using TOOHUCardAPI.Data.Models; namespace TOOHUCardAPI.Data.Repositories { public class UserRepository { private readonly AppDbContext _appDbContext; private readonly IMapper _mapper; public UserRepository(AppDbContext appDbContext, IMapper mapper) { _appDbContext = appDbContext; _mapper = mapper; } private IQueryable GetAllUsersQuery() { return _appDbContext.Users .Include(u => u.EncodedCardGroups) .Include(u => u.CardLevels) .ThenInclude(cl => cl.Card) .AsSingleQuery() .AsQueryable(); } public async Task GetUser(long steamId, bool allowNull = false) { User user = await GetAllUsersQuery().FirstOrDefaultAsync(user => user.SteamId.Equals(steamId)); if (user == null && !allowNull) { throw new InvalidUserException(); } return user; } public async Task CreateUser(long steamId) { User user = new User { SteamId = steamId, Vip = true, EndTime = DateTime.MaxValue, PetLevel = 1, PetModel = "h000", PetEffect = "e000", EncodedCardGroups = new List { new() { EncodedString = AppSettings.StarterDeckGroupData, GroupKey = AppSettings.StarterDeckGroupKey } } }; await _appDbContext.Users.AddAsync(user); await _appDbContext.SaveChangesAsync(); return user; } public async Task UpdateUser(User user) { var trackedUser = GetAllUsersQuery().FirstOrDefault(u => u.SteamId == user.SteamId); if (trackedUser == default) { return null; } _appDbContext.Update(user); await _appDbContext.SaveChangesAsync(); return user; } public async Task GetOrCreateUser(long steamId) { User user = await GetUser(steamId, true) ?? await CreateUser(steamId); return user; } } }