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 DrugController : Controller
	{
		private readonly ILogger _logger;
		private readonly IDrugLogic _drug;
		public DrugController(ILogger<DrugController> logger, IDrugLogic drug)
		{
			_logger = logger;
			_drug = drug;
		}
		[HttpGet]
		public Tuple<DrugViewModel, List<Tuple<string, int>>>? GetDrug(int drugId)
		{
			try
			{
				var elem = _drug.ReadElement(new DrugSearchModel { Id = drugId });
				if (elem == null)
					return null;
				var res = Tuple.Create(elem, elem.DrugMedications.Select(x => Tuple.Create(x.Value.MedicationName, x.Value.Id)).ToList());
				res.Item1.DrugMedications = null!;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения услуги по id={Id}", drugId);
				throw;
			}
		}
		[HttpGet]
		public DrugViewModel? GetOneDrug(int drugId)
		{
			try
			{
				var elem = _drug.ReadElement(new DrugSearchModel{Id =drugId});
				if (elem == null)
					return null;
				elem.DrugMedications = null!;
				return elem;

			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения лекарства по id={Id}",drugId);
				throw;
			}
		}

		[HttpGet]
		public List<DrugViewModel> GetDrugs(int? doctorId = null)
		{
			try
			{
				List<DrugViewModel> res;
				if (!doctorId.HasValue)
					res = _drug.ReadList(null);
				else
					res = _drug.ReadList(new DrugSearchModel { DoctorId = doctorId.Value });
				foreach (var drug in res)
					drug.DrugMedications = null;
				return res;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка услуг");
				throw;
			}
		}
		[HttpGet]
		public List<DrugViewModel> GetAllDrugs(int doctorId)
		{
			try
			{
				return _drug.ReadList(null);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка лекартсв");
				throw;
			}
		}
		[HttpPost]
		public bool CreateDrug(DrugBindingModel model)
		{
			try
			{
				return _drug.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать лекарств");
				throw;
			}
		}

		[HttpPost]
		public bool UpdateDrug(DrugBindingModel model)
		{
			try
			{
				//model.DrugMedications = null!;
				return _drug.Update(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось обновить лекарства");
				throw;
			}
		}

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