using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDatabaseImplement.Models;
using SoftwareInstallationDataModels;
using SoftwareInstallationDataModels.Models;
using Microsoft.EntityFrameworkCore;

namespace SoftwareInstallationDatabaseImplement
{
    public class ShopStorage : IShopStorage
    {

        public ShopViewModel? Delete(ShopBindingModel model)
        {
            using var context = new SoftwareInstallationDatabase();
            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 SoftwareInstallationDatabase();
            return context.Shops
                .Include(x => x.ShopPackages)
                .ThenInclude(x => x.Package)
                .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 SoftwareInstallationDatabase();
            return context.Shops
                .Include(x => x.ShopPackages)
                .ThenInclude(x => x.Package)
                .Select(x => x.GetViewModel)
                .Where(x => x.Name.Contains(model.Name ?? string.Empty))
                .ToList();
        }

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

        public ShopViewModel? Insert(ShopBindingModel model)
        {
            using var context = new SoftwareInstallationDatabase();
            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 SoftwareInstallationDatabase();
            var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
            if (shop == null)
            {
                return null;
            }
            shop.Update(model);
            shop.UpdatePackages(context, model);
            context.SaveChanges();
            return shop.GetViewModel;
        }

        public bool HasNeedPackages(IPackageModel package, int needCount)
        {
            throw new NotImplementedException();
        }

        public bool SellPackages(IPackageModel package, int needCount)
        {
            using var context = new SoftwareInstallationDatabase();
            using var transaction = context.Database.BeginTransaction();
            foreach (var sp in context.ShopPackages.Where(x => x.PackageId == package.Id))
            {
                var res = Math.Min(needCount, sp.Count);
                sp.Count -= res;
                needCount -= res;
                if (sp.Count == 0) // Изделия больше нет в магазине, значит удаляем его
                {
                    context.ShopPackages.Remove(sp);
                }
                if (needCount == 0) // Нельзя коммитить изменения в цикле, что использует контекст, поэтому выходим
                {
                    break;
                }
            }
            if (needCount == 0)
            {
                context.SaveChanges();
                transaction.Commit();
            }
            else
            {
                transaction.Rollback();
            }
            return needCount == 0;
        }
    }
}
