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

namespace VeterinaryDatabaseImplement.Implements
{
	public class VisitStorage : IVisitStorage
	{
		public List<VisitViewModel> GetFullList()
		{
			using var context = new VeterinaryDatabase();
			return context.Visits.Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Owner)
			.Include(x => x.Doctor).Select(x => x.GetViewModel)
		   .ToList();
		}
		public List<VisitViewModel> GetFilteredList(VisitSearchModel model)
		{

			using var context = new VeterinaryDatabase();
			return context.Visits.Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Doctor)
				.Where(x => x.OwnerId == model.OwnerId)
				.Where(x => ((!model.Id.HasValue || x.Id == model.Id) &&
						(string.IsNullOrEmpty(model.VisitName) || x.VisitName.Contains(model.VisitName)) &&
						(!model.DateVisit.HasValue || x.DateVisit >= model.DateVisit) &&
						(!model.OwnerId.HasValue || x.OwnerId <= model.OwnerId) &&
						(!model.DoctorId.HasValue || x.DoctorId == model.DoctorId)))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public VisitViewModel? GetElement(VisitSearchModel model)
		{
			if (string.IsNullOrEmpty(model.VisitName) && !model.Id.HasValue)
			{
				return null;
			}
			using var context = new VeterinaryDatabase();
			return context.Visits.Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Doctor)
				.FirstOrDefault(x => (!string.IsNullOrEmpty(model.VisitName) && x.VisitName == model.VisitName) || (x.Id == model.Id))?.GetViewModel;
		}
		public VisitViewModel? Insert(VisitBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var newVisit = Visit.Create(context, model);
			if (newVisit == null)
			{
				return null;
			}
			context.Visits.Add(newVisit);
			context.SaveChanges();
			return newVisit.GetViewModel;
		}
		public VisitViewModel? Update(VisitBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var visit = context.Visits.Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Owner)
				.FirstOrDefault(x => x.Id == model.Id);
			if (visit == null)
			{
				return null;
			}
			visit.Update(model);
			//visit.UpdateVisits(context, model);
			context.SaveChanges();
			return visit.GetViewModel;
		}
		public VisitViewModel? Delete(VisitBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var element = context.Visits.Include(x => x.Owner).Include(x => x.Pets).Include(x => x.Doctor).FirstOrDefault
				(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Visits.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
