using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDatabaseImplement.Models;
using AbstractIceCreamShopDataModels.Models;
using Microsoft.EntityFrameworkCore;

namespace IceCreamShopDatabaseImplement.Implements
{
    public class ShopStorage : IShopStorage
    {

        public ShopViewModel? Delete(ShopBindingModel model)
        {
            using var context = new IceCreamShopDatabase();
            var element = context.Shops.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                context.Shops.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }

        public ShopViewModel? GetElement(ShopSearchModel model)
        {
            if (!model.Id.HasValue)
            {
                return null;
            }
            using var context = new IceCreamShopDatabase();
            return context.Shops
                .Include(x => x.IceCreams)
                .ThenInclude(x => x.IceCream)
                .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
                ?.GetViewModel;
        }

        public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                return new();
            }
            using var context = new IceCreamShopDatabase();
            return context.Shops
                .Include(x => x.IceCreams)
                .ThenInclude(x => x.IceCream)
                .Select(x => x.GetViewModel)
                .Where(x => x.Name.Contains(model.Name ?? string.Empty))
                .ToList();
        }

        public List<ShopViewModel> GetFullList()
        {
            using var context = new IceCreamShopDatabase();
            return context.Shops
                .Include(x => x.IceCreams)
                .ThenInclude(x => x.IceCream)
                .Select(shop => shop.GetViewModel)
                .ToList();
        }

        public ShopViewModel? Insert(ShopBindingModel model)
        {
            using var context = new IceCreamShopDatabase();
            using var transaction = context.Database.BeginTransaction();
            try
            {
                var newShop = Shop.Create(context, model);
                if (newShop == null)
                {
                    return null;
                }
                if (context.Shops.Any(x => x.Name == newShop.Name))
                {
                    throw new Exception("Не должно быть два магазина с одним названием");
                }
                context.Shops.Add(newShop);
                context.SaveChanges();
                transaction.Commit();
                return newShop.GetViewModel;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }

        public ShopViewModel? Update(ShopBindingModel model)
        {
            using var context = new IceCreamShopDatabase();
            using var transaction = context.Database.BeginTransaction();
            try
            {
                var shop = context.Shops.Include(x => x.IceCreams).FirstOrDefault(x => x.Id == model.Id);
                if (shop == null)
                {
                    return null;
                }
                shop.Update(model);
                context.SaveChanges();
                if (model.ShopIceCreams.Count > 0)
                {
                    shop.UpdateIceCreams(context, model);
                }
                transaction.Commit();
                return shop.GetViewModel;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }

        public bool SellIceCreams(IIceCreamModel icecream, int needCount)
        {
            using var context = new IceCreamShopDatabase();
            using var transaction = context.Database.BeginTransaction();
            foreach (var shopDocs in context.ShopIcecreams.Where(x => x.IceCreamId == icecream.Id))
            {
                var min = Math.Min(needCount, shopDocs.Count);
                shopDocs.Count -= min;
                needCount -= min;
                if (needCount <= 0)
                {
                    break;
                }
            }
            if (needCount == 0)
            {
                context.SaveChanges();
                transaction.Commit();
            }
            else
            {
                transaction.Rollback();
            }
            if (needCount > 0)
            {
                return false;
            }
            return true;
        }
    }
}
