using AbstractShopContracts.BindingModels;
using AbstractShopContracts.SearchModels;
using AbstractShopContracts.StoragesContracts;
using AbstractShopContracts.ViewModels;
using AbstractShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;

namespace AbstractShopDatabaseImplement.Implements
{
    public class ProductStorage : IProductStorage
    {
		public List<ProductViewModel> GetFullList()
		{
			using var context = new AbstractShopDatabase();
			return context.Products
					.Include(x => x.Components)
					.ThenInclude(x => x.Component)
					.ToList()
					.Select(x => x.GetViewModel)
					.ToList();
		}

		public List<ProductViewModel> GetFilteredList(ProductSearchModel model)
		{
			if (string.IsNullOrEmpty(model.ProductName))
			{
				return new();
			}
			using var context = new AbstractShopDatabase();
			return context.Products
					.Include(x => x.Components)
					.ThenInclude(x => x.Component)
					.Where(x => x.ProductName.Contains(model.ProductName))
					.ToList()
					.Select(x => x.GetViewModel)
					.ToList();
		}

		public ProductViewModel? GetElement(ProductSearchModel model)
		{
			if (string.IsNullOrEmpty(model.ProductName) && !model.Id.HasValue)
			{
				return null;
			}
			using var context = new AbstractShopDatabase();
			return context.Products
				.Include(x => x.Components)
				.ThenInclude(x => x.Component)
				.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ProductName) && x.ProductName == model.ProductName) ||
								(model.Id.HasValue && x.Id == model.Id))
				?.GetViewModel;
		}

		public ProductViewModel? Insert(ProductBindingModel model)
		{
			using var context = new AbstractShopDatabase();
			var newProduct = Product.Create(context, model);
			if (newProduct == null)
			{
				return null;
			}
			context.Products.Add(newProduct);
			context.SaveChanges();
			return newProduct.GetViewModel;
		}

		public ProductViewModel? Update(ProductBindingModel model)
		{
			using var context = new AbstractShopDatabase();
			using var transaction = context.Database.BeginTransaction();
			try
			{
				var product = context.Products.FirstOrDefault(rec => rec.Id == model.Id);
				if (product == null)
				{
					return null;
				}
				product.Update(model);
				context.SaveChanges();
				product.UpdateComponents(context, model);
				transaction.Commit();
				return product.GetViewModel;
			}
			catch
			{
				transaction.Rollback();
				throw;
			}
		}

		public ProductViewModel? Delete(ProductBindingModel model)
		{
			using var context = new AbstractShopDatabase();
			var element = context.Products
				.Include(x => x.Components)
				.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Products.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}