using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using TOOHUCardAPI.Data.Models; using TOOHUCardAPI.Data.Repositories; using TOOHUCardAPI.DTO; namespace TOOHUCardAPI.Data.Services { public class StoreService { private readonly ILogger _logger; private readonly UserRepository _userRepository; public StoreService(ILogger logger, UserRepository userRepository) { _logger = logger; _userRepository = userRepository; } private void AddPoints(int points, User user) { user.Point = Math.Max(0, user.Point + points); _userRepository.UpdateUser(user); _logger.LogInformation($"User with steamid {user.SteamId} was given {points} points. New total: {user.Point}"); } public async Task PurchaseMagicKey(int amt, string steamId) { int totalCost = AppSettings.PointsPerKey * amt; amt = Math.Clamp(amt, 0, AppSettings.MaxKeyPurchaseAmount); User user = _userRepository.GetUser(steamId); if (user == null) { throw new InvalidUserException(); } if (user.Point < totalCost) { throw new InsufficientPointsException(); } AddPoints(-totalCost, user); user.KeyTotal += amt; _userRepository.UpdateUser(user); _logger.LogInformation($"User with steamid {user.SteamId} purchased {amt} keys for {totalCost} points. New point value is {user.Point}"); return totalCost; } public async Task GiveFirstWinBonus(string steamId) { User user = _userRepository.GetUser(steamId); if (user == null) { throw new InvalidUserException(); } if (user.LastFirstWin.AddDays(1) > DateTime.Now) { throw new NotFirstWinException(); } AddPoints(AppSettings.FirstWinBonusPoints, user); user.LastFirstWin = DateTime.Now; _userRepository.UpdateUser(user); _logger.LogInformation($"User with steamid {user.SteamId} received first win of the day bonus, earning {AppSettings.FirstWinBonusPoints} points. New value: {user.Point}"); return AppSettings.FirstWinBonusPoints; } } public class InsufficientPointsResponse : AbstractResponse { public InsufficientPointsResponse() { Code = "0002"; Message = "Insufficient points"; } } public class NotFirstWinResponse : AbstractResponse { public NotFirstWinResponse() { Code = "0003"; Message = "Not first win of the day"; } } }