using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.ViewModels;
using VeterinaryDataModels.Models;

namespace VeterinaryDatabaseImplement.Models
{
    public class Purchase : IPurchaseModel
	{
		public int Id { get; private set; }
		[Required]
		public int OwnerId { get; private set; }
		public virtual Owner? Owner { get; private set; }
		[Required]
		public int DrugId { get; private set; }
		public virtual Drug? Drug { get; private set; }
		[Required]
		public int Count { get; private set; }
		[Required]
		public double Sum { get; private set; }
		[Required]
		public DateTime DateCreate { get; private set; }
		private Dictionary<int, IPetModel>? _purchasePet = null;
		[NotMapped]
		public Dictionary<int, IPetModel> PurchasePet
		{
			get
			{
				if (_purchasePet == null)
				{
					_purchasePet = Pets
					.ToDictionary(recPC => recPC.PetId, recPC =>
				   (recPC.Pet as IPetModel));
				}
				return _purchasePet;
			}
		}
		[ForeignKey("PurchaseId")]
		public virtual List<PurchasePet> Pets { get; set; } = new();
		public static Purchase? Create(VeterinaryDatabase context, PurchaseBindingModel model)
		{
			return new Purchase()
			{
				Id = model.Id,
				Count = model.Count,
				Sum = model.Sum,
				OwnerId = model.OwnerId,
				DrugId = model.DrugId,
				DateCreate = model.DateCreate,
				Pets = model.PurchasePet.Select(x => new PurchasePet
				{
					Pet = context.Pets.First(y => y.Id == x.Key),

				}).ToList()
			};
		}
		public PurchaseViewModel GetViewModel => new()
		{
			Id = Id,
			Count = Count,
			Sum = Sum,
			OwnerId = OwnerId,
			DrugId = DrugId,
			DrugName = Drug?.DrugName ?? string.Empty,
			DateCreate = DateCreate
		};
	}
}
