using AutoMapper; using SessionCompanion.Database.Repositories.Base; using SessionCompanion.Database.Tables; using SessionCompanion.Services.Base; using SessionCompanion.Services.Interfaces; using SessionCompanion.ViewModels.ShopkeeperItemsViewModels; using System; using System.Threading.Tasks; namespace SessionCompanion.Services.Services { using System.Linq; using Microsoft.EntityFrameworkCore; using SessionCompanion.Extensions.EitherType; using SessionCompanion.ViewModels.ApiResponses; using SessionCompanion.ViewModels.ShopkeeperViewModels; public class ShopkeeperItemService : ServiceBase, IShopkeeperItemService { public ShopkeeperItemService(IMapper mapper, IRepository repository) : base(mapper, repository) { } public async Task> GetActiveShkopkeeperWithItems(int shopkeeperId, int amount, int? weaponId, int? armorId) { try { var shopkeeperItem = await Repository.Get(c => c.ShopkeeperId.Equals(shopkeeperId) && c.WeaponId.Equals(weaponId) && c.ArmorId.Equals(armorId)).FirstOrDefaultAsync(); if (shopkeeperItem == null) { throw new Exception("Shopkeeper with given id's couldn't have been found"); } if (shopkeeperItem.Amount - amount < 0) { throw new Exception("Shopkeeper does not have that quantity of the item"); } else if (shopkeeperItem.Amount - amount == 0) { this.Repository.Delete(shopkeeperItem); await this.Repository.Save(); return new SuccessResponse("Items were deducted from the shopkeeper"); } else { shopkeeperItem.Amount -= amount; await this.Repository.Update(shopkeeperItem); await this.Repository.Save(); return new SuccessResponse("Items were deducted from the shopkeeper"); } } catch (Exception e) { return new ErrorResponse() { StatusCode = 500, Message = e.Message }; } } } }