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 MedicineController : Controller
	{
		private readonly ILogger _logger;
		private readonly IMedicineLogic _medicine;
		public MedicineController(ILogger<MedicineController> logger, IMedicineLogic medicine)
		{
			_logger = logger;
			_medicine = medicine;
		}

		[HttpGet]
		public Tuple<MedicineViewModel, List<string>>? GetMedicine(int medicineId)
		{
			try
			{
				var elem = _medicine.ReadElement(new MedicineSearchModel { Id = medicineId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.MedicineAnimals.Select(x => x.Value.AnimalName).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения медикамента по id={Id}", medicineId);
				throw;
			}
		}
		[HttpGet]
		public List<MedicineViewModel> GetMedicines(int pharmacistId)
		{
			try
			{
				return _medicine.ReadList(new MedicineSearchModel { PharmacistId = pharmacistId});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка медикаментов");
				throw;
			}
		}
		[HttpPost]
		public bool CreateMedicine(MedicineBindingModel model)
		{
			try
			{
				return _medicine.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать медикамент");
				throw;
			}
		}

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

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