using Microsoft.EntityFrameworkCore;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Models;

namespace VeterinaryDatabaseImplement.Implements
{
	public class PurchaseStorage : IPurchaseStorage
	{
		public List<PurchaseViewModel> GetFullList()
		{
			using var context = new VeterinaryDatabase();
			return context.Purchases.Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Owner)
			.Include(x => x.Drug).Select(x => x.GetViewModel)
		   .ToList();
		}
		public List<PurchaseViewModel> GetFilteredList(PurchaseSearchModel model)
		{ 
			using var context = new VeterinaryDatabase();
			return context.Purchases.Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Drug)
				.Where(x => x.OwnerId == model.OwnerId)
				.Where(x => ((!model.Id.HasValue || x.Id == model.Id) &&
						(!model.DateCreate.HasValue || x.DateCreate >= model.DateCreate) &&
						(!model.OwnerId.HasValue || x.OwnerId <= model.OwnerId) &&
						(!model.DrugId.HasValue || x.DrugId == model.DrugId)))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public PurchaseViewModel? GetElement(PurchaseSearchModel model)
		{
			if (!model.Id.HasValue)
			{
				return null;
			}
			using var context = new VeterinaryDatabase();
			return context.Purchases.Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Drug)
				.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
		}
		public PurchaseViewModel? Insert(PurchaseBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var newPurchase = Purchase.Create(context, model);
			if (newPurchase == null)
			{
				return null;
			}
			context.Purchases.Add(newPurchase);
			context.SaveChanges();
			return newPurchase.GetViewModel;
		}
	}
}
