using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Mvc;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Models;

namespace VeterinaryRestApi.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<Tuple<string, int>>>? GetVisit(int visitId)
		{
			try
			{
				var elem = _visit.ReadElement(new VisitSearchModel { Id = visitId });
				if (elem == null)
					return null;
				var res = Tuple.Create(elem, elem.VisitPet.Select(x => Tuple.Create(x.Value.PetName, x.Value.Id)).ToList());
				res.Item1.VisitPet = null!;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения визита по id={Id}", visitId);
				throw;
			}
		}
		[HttpGet]
		public List<VisitViewModel>? GetVisits(int? ownerId = null)
		{
			try
			{
				List<VisitViewModel> res;
				if (!ownerId.HasValue)
					res = _visit.ReadList(null);
				else
					res = _visit.ReadList(new VisitSearchModel { OwnerId = ownerId.Value });
				foreach (var service in res)
					service.VisitPet = null;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка визитов");
				throw;
			}
		}

		[HttpGet]
		public List<VisitViewModel> GetAllVisits()
		{
			try
			{
				return _visit.ReadList(null);
			}
			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
			{
				return _visit.Update(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось обновить лекарства");
				throw;
			}
		}
	}
}
