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

namespace VetClinicRestApi.Controllers
{
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class VisitController : Controller
	{
		private readonly ILogger _logger;
		private readonly IVisitLogic _visit;
		public VisitController(ILogger<VisitController> logger, IVisitLogic visit)
		{
			_logger = logger;
			_visit = visit;
		}

		[HttpGet]
		public Tuple<VisitViewModel, List<string>>? GetVisit(int VisitId)
		{
			try
			{
				var elem = _visit.ReadElement(new VisitSearchModel { Id = VisitId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.VisitAnimals.Select(x => x.Value.AnimalName).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения визита по id={Id}", VisitId);
				throw;
			}
		}
		[HttpGet]
		public List<VisitViewModel> GetVisits(int adminId)
		{
			try
			{
				return _visit.ReadList(new VisitSearchModel { AdminId = adminId});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка визитовв");
				throw;
			}
		}
		[HttpPost]
		public bool CreateVisit(VisitBindingModel model)
		{
			try
			{
				return _visit.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать визит");
				throw;
			}
		}

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

		[HttpPost]
		public bool DeleteVisit(VisitBindingModel model)
		{
			try
			{
				return _visit.Delete(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка удаления визита");
				throw;
			}
		}
	}
}
