using VetClinicContracts.BindingModels;
using VetClinicContracts.SearchModels;
using VetClinicContracts.StoragesContracts;
using VetClinicContracts.ViewModels;
using VetClinicDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using VetClinicDataBaseImplement;

namespace VetClinicBaseImplement.Implements
{
	public class AnimalStorage : IAnimalStorage
	{
		public List<AnimalViewModel> GetFullList()
		{
			using var context = new VetClinicDatabase();

			return context.Animals
					 .Include(x => x.Admin)
					.Select(x => x.GetViewModel)
					.ToList();
		}
		public List<AnimalViewModel> GetFilteredList(AnimalSearchModel model)
		{

			if (string.IsNullOrEmpty(model.AnimalName))
			{
				return new();
			}
			using var context = new VetClinicDatabase();
			return context.Animals
			 .Include(x => x.Admin)
			.Where(x => x.AnimalName.Contains(model.AnimalName))
			.ToList()
			.Select(x => x.GetViewModel).ToList();
		}
		public AnimalViewModel? GetElement(AnimalSearchModel model)
		{
			if (!model.Id.HasValue)
			{
				return null;
			}
			using var context = new VetClinicDatabase();
			return context.Animals
				 .Include(x => x.Admin)
			.Include(x => x.Vaccinations)
			 .FirstOrDefault(x => (!string.IsNullOrEmpty(model.AnimalName) && x.AnimalName == model.AnimalName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
		}
		public AnimalViewModel? Insert(AnimalBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var newAnimal = Animal.Create(context,model);
			if (newAnimal == null)
			{
				return null;
			}
			context.Animals.Add(newAnimal);
			context.SaveChanges();
			return newAnimal.GetViewModel;
		}
		public AnimalViewModel? Update(AnimalBindingModel model)
		{
			using var context = new VetClinicDatabase();
			using var transaction = context.Database.BeginTransaction();
		
			try
			{
				var animal = context.Animals.FirstOrDefault(rec => rec.Id == model.Id);
				if (animal == null)
				{
					return null;
				}
				animal.Update(model);
				context.SaveChanges();
				transaction.Commit();
				return animal.GetViewModel;
			}
			catch
			{
				transaction.Rollback();
				throw;
			}
		}
		public AnimalViewModel? Delete(AnimalBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Animals
					.Include(x => x.Vaccinations)
			.FirstOrDefault(rec => rec.Id == model.Id);

			if (element != null)
			{
				context.Animals.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
