session-companion/SessionCompanion/SessionCompanion.Services/Services/ShopkeeperService.cs

44 lines
1.7 KiB
C#

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SessionCompanion.Database.Repositories.Base;
using SessionCompanion.Database.Tables;
using SessionCompanion.Extensions.EitherType;
using SessionCompanion.Services.Base;
using SessionCompanion.Services.Interfaces;
using SessionCompanion.ViewModels.ApiResponses;
using SessionCompanion.ViewModels.ShopkeeperViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SessionCompanion.Services.Services
{
public class ShopkeeperService : ServiceBase<ShopkeeperViewModel, Shopkeeper>, IShopkeeperService
{
public ShopkeeperService(IMapper mapper, IRepository<Shopkeeper> repository) : base(mapper, repository)
{ }
public async Task<Either<SuccessResponse, ErrorResponse>> CreateNewShopKeeper(ShopkeeperWithItemsViewModel shopkeeperWithItemsViewModel)
{
try
{
var activeShopkeeper = await Repository.Get(c => c.IsAvailable.Equals(true)).SingleAsync();
if (activeShopkeeper is not null && shopkeeperWithItemsViewModel.IsAvailable)
{
activeShopkeeper.IsAvailable = false;
await Repository.Update(activeShopkeeper);
}
var result = Mapper.Map<Shopkeeper>(shopkeeperWithItemsViewModel);
await Repository.Create(result);
await Repository.Save();
return new SuccessResponse("New shopkeeper created");
}
catch (Exception e)
{
return new ErrorResponse() { StatusCode = 500, Message = e.Message };
}
}
}
}