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<string>>? GetDrug(int drugId)
		{
			try
			{
				var elem = _drug.ReadElement(new DrugSearchModel { Id = drugId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.DrugMedications.Select(x => x.Value.MedicationName).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения услуги по id={Id}", drugId);
				throw;
			}
		}
		[HttpGet]
		public List<DrugViewModel> GetDrugs(int doctorId)
		{
			try
			{
				return _drug.ReadList(new DrugSearchModel { DoctorId = doctorId });
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка лекартсв");
				throw;
			}
		}
		[HttpPost]
		public bool CreateDrug(DrugBindingModel model)
		{
			try
			{
				foreach(var medication in model.DrugMedications)
				{
					model.Price += medication.Value.Price;
				}
				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;
			}
		}
	}
}
