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 ServiceController : Controller
	{
		private readonly ILogger _logger;
		private readonly IServiceLogic _service;
		public ServiceController(ILogger<ServiceController> logger, IServiceLogic service)
		{
			_logger = logger;
			_service = service;
		}

		[HttpGet]
		public Tuple<ServiceViewModel, List<Tuple<string, int>>>? GetService(int serviceId)
		{
			try
			{
				var elem = _service.ReadElement(new ServiceSearchModel { Id = serviceId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.ServiceMedicines.Select(x => Tuple.Create(x.Value.Item1.MedicineName, x.Value.Item2)).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения услуги по id={Id}", serviceId);
				throw;
			}
		}
		[HttpGet]
		public List<ServiceViewModel> GetServices(int pharmacistId)
		{
			try
			{
				return _service.ReadList(new ServiceSearchModel { PharmacistId = pharmacistId });
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка услуг");
				throw;
			}
		}
		[HttpPost]
		public bool CreateService(ServiceBindingModel model)
		{
			try
			{
				return _service.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать услугу");
				throw;
			}
		}

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

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


	}
}
