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 PurchaseController : Controller
	{
		private readonly ILogger _logger;
		private readonly IPurchaseLogic _purchase;
		public PurchaseController(ILogger<PurchaseController> logger, IPurchaseLogic purchase)
		{
			_logger = logger;
			_purchase = purchase;
		}
		[HttpGet]
		public Tuple<PurchaseViewModel, List<string>>? GetPurchase(int purchaseId)
		{
			try
			{
				var elem = _purchase.ReadElement(new PurchaseSearchModel { Id = purchaseId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.PurchasePet.Select(x => x.Value.PetName).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения покупки по id={Id}", purchaseId);
				throw;
			}
		}
		[HttpGet]
		public List<PurchaseViewModel>? GetPurchases()
		{
			try
			{
				return _purchase.ReadList(null);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка покупок");
				throw;
			}
		}
		[HttpPost]
		public bool CreatePurchase(PurchaseBindingModel model)
		{
			try
			{
				return _purchase.CreatePurchase(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать покупку");
				throw;
			}
		}
	}
}
