using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VetClinicContracts.BindingModels;
using VetClinicContracts.BusinessLogicsContracts;
using VetClinicContracts.SearchModels;
using VetClinicContracts.ViewModels;
using VetClinicDataBaseImplement.Models;

namespace VetClinicRestApi.Controllers
{
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class AnimalController : Controller
	{
		private readonly ILogger _logger;
		private readonly IAnimalLogic _animal;
		public AnimalController(ILogger<AnimalController> logger, IAnimalLogic animal)
		{
			_logger = logger;
			_animal = animal;
		}

		[HttpGet]
		public Tuple<AnimalViewModel, List<Tuple<string, int>>>? GetAnimal(int animalId)
		{
			try
			{
				var elem = _animal.ReadElement(new AnimalSearchModel { Id = animalId });
				if (elem == null)
					return null;
				var res = Tuple.Create(elem, elem.VisitAnimals.Select(x => Tuple.Create(x.Value.NameVisit, x.Value.Id)).ToList());
				res.Item1.VisitAnimals = null!;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения животного по id={Id}", animalId);
				throw;
			}
		}

		[HttpGet]
		public List<AnimalViewModel>? GetAnimalList(int? adminId = null)
		{
			try
			{
				List<AnimalViewModel> res;
				if (!adminId.HasValue)
					res = _animal.ReadList(null);
				else
					res = _animal.ReadList(new AnimalSearchModel { AdminId = adminId });
				foreach (var animal in res)
					animal.VisitAnimals = null;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка животных");
				throw;
			}
		}
			[HttpPost]
		public bool CreateAnimal(AnimalBindingModel model)
		{
			try
			{
				return _animal.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать животное");
				throw;
			}
		}

		[HttpPost]
		public bool UpdateAnimal(bool isConnection,AnimalBindingModel model)
		{
			try
			{
				if (!isConnection)
					model.VisitAnimals = null!;
				return _animal.Update(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось обновить животное");
				throw;
			}
		}

		[HttpPost]
		public bool DeleteAnimal(AnimalBindingModel model)
		{
			try
			{
				return _animal.Delete(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка удаления услуги");
				throw;
			}
		}


	}
}
