using Microsoft.Extensions.Logging;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.ViewModels;

namespace VeterinaryBusinessLogic.BusinessLogic
{
	public class PurchaseLogic : IPurchaseLogic
	{
		private readonly ILogger _logger;
		private readonly IPurchaseStorage _purchaseStorage;

		public PurchaseLogic(ILogger<PurchaseLogic> logger, IPurchaseStorage purchaseStorage)
		{
			_logger = logger;
			_purchaseStorage = purchaseStorage;
		}

		public PurchaseViewModel? ReadElement(PurchaseSearchModel model)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
			var element = _purchaseStorage.GetElement(model);
			if (element == null)
			{
				_logger.LogWarning("ReadElement element not found");
				return null;
			}
			_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
			return element;
		}

		public List<PurchaseViewModel>? ReadList(PurchaseSearchModel? model)
		{
			_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
			var list = model == null ? _purchaseStorage.GetFullList() : _purchaseStorage.GetFilteredList(model);
			if (list == null)
			{
				_logger.LogWarning("ReadList return null list");
				return null;
			}
			_logger.LogInformation("ReadList. Count:{Count}", list.Count);
			return list;
		}

		public bool CreatePurchase(PurchaseBindingModel model)
		{
			CheckModel(model);
			if (_purchaseStorage.Insert(model) == null)
			{
				_logger.LogWarning("Insert operation failed");
				return false;
			}
			return true;
		}
		private void CheckModel(PurchaseBindingModel model, bool withParams = true)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			if (!withParams)
			{
				return;
			}
			if (model.Sum <= 0)
			{
				throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
			}
			//if (model.DateCreate < DateTime.Now)
			//{
			//	throw new ArgumentNullException("Дата покупки не должна быть в прошлом", nameof(model.DateCreate));
			//}
			if (model.Count <= 0)
			{
				throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
			}
			_logger.LogInformation("Purchase. DatePuchase: { DatePurchase}. Count:{ Count}. Id: { Id}", model.DateCreate, model.Count, model.Id);
		}
	}
}
