using SecureShopContracts.BindingModels;
using SecureShopContracts.SearchModels;
using SecureShopContracts.StoragesContracts;
using SecureShopContracts.ViewModels;
using SecureShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;

namespace SecureShopDatabaseImplement.Implements
{
    public class SecureStorage : ISecureStorage
    {
		public List<SecureViewModel> GetFullList()
		{
			using var context = new SecureShopDatabase();
			return context.Secures
					.Include(x => x.Facilitiess)
					.ThenInclude(x => x.Facilities)
					.ToList()
					.Select(x => x.GetViewModel)
					.ToList();
		}

		public List<SecureViewModel> GetFilteredList(SecureSearchModel model)
		{
			if (string.IsNullOrEmpty(model.SecureName))
			{
				return new();
			}
			using var context = new SecureShopDatabase();
			return context.Secures
					.Include(x => x.Facilitiess)
					.ThenInclude(x => x.Facilities)
					.Where(x => x.SecureName.Contains(model.SecureName))
					.ToList()
					.Select(x => x.GetViewModel)
					.ToList();
		}

		public SecureViewModel? GetElement(SecureSearchModel model)
		{
			if (string.IsNullOrEmpty(model.SecureName) && !model.Id.HasValue)
			{
				return null;
			}
			using var context = new SecureShopDatabase();
			return context.Secures
				.Include(x => x.Facilitiess)
				.ThenInclude(x => x.Facilities)
				.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SecureName) && x.SecureName == model.SecureName) ||
								(model.Id.HasValue && x.Id == model.Id))
				?.GetViewModel;
		}

		public SecureViewModel? Insert(SecureBindingModel model)
		{
			using var context = new SecureShopDatabase();
			var newSecure = Secure.Create(context, model);
			if (newSecure == null)
			{
				return null;
			}
			context.Secures.Add(newSecure);
			context.SaveChanges();
			return newSecure.GetViewModel;
		}

		public SecureViewModel? Update(SecureBindingModel model)
		{
			using var context = new SecureShopDatabase();
			using var transaction = context.Database.BeginTransaction();
			try
			{
				var Secure = context.Secures.FirstOrDefault(rec => rec.Id == model.Id);
				if (Secure == null)
				{
					return null;
				}
				Secure.Update(model);
				context.SaveChanges();
				Secure.UpdateFacilitiess(context, model);
				transaction.Commit();
				return Secure.GetViewModel;
			}
			catch
			{
				transaction.Rollback();
				throw;
			}
		}

		public SecureViewModel? Delete(SecureBindingModel model)
		{
			using var context = new SecureShopDatabase();
			var element = context.Secures
				.Include(x => x.Facilitiess)
				.Include(x => x.Orders)
				.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Secures.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
