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 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.ServiceVisits.Select(x => Tuple.Create(x.Value.ServiceName, x.Value.Id)).ToList());
				res.Item1.ServiceVisits = null;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения визита по id={Id}", VisitId);
				throw;
			}
		}
		[HttpGet]
		public List<VisitViewModel> GetVisits(int? adminId = null)
		{
			try
			{
				List<VisitViewModel> res;
				if (!adminId.HasValue)
					res = _visit.ReadList(null);
				else
					res = _visit.ReadList(new VisitSearchModel { AdminId = adminId });
				foreach (var visit in res)
					visit.ServiceVisits = null!;
				return res;
			}
			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(bool isConnection,VisitBindingModel model)
		{
			try
			{
				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;
			}
		}
	}
}
