using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;

namespace BlacksmithWorkshopRestApi.Controllers
{
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class ShopController : ControllerBase
	{
		private readonly ILogger _logger;
		private readonly IShopLogic _logic;
		public ShopController(IShopLogic logic, ILogger<ShopController> logger)
		{
			_logger = logger;
			_logic = logic;
		}
		[HttpGet]
		public Tuple<ShopViewModel, List<Tuple<string, int>>>? GetShop(int shopId)
		{
			try
			{
				var elem = _logic.ReadElement(new ShopSearchModel { Id = shopId });
				if (elem == null)
					return null;
				return Tuple.Create(elem, elem.ShopManufactures.Select(x => Tuple.Create(x.Value.Item1.ManufactureName, x.Value.Item2)).ToList());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения магазина по id={Id}", shopId);
				throw;
			}
		}
		[HttpGet]
		public List<ShopViewModel> GetShops()
		{
			try
			{
				return _logic.ReadList(null);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка получения списка магазинов");
				throw;
			}
		}
		[HttpPost]
		public bool CreateShop(ShopBindingModel model)
		{
			try
			{
				return _logic.Create(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось создать магазин");
				throw;
			}
		}

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

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

		[HttpPost]
		public bool MakeSupply(Tuple<ShopSearchModel, ManufactureViewModel, int> model)
		{
			try
			{
				return _logic.ReplenishManufactures(model.Item1, model.Item2, model.Item3);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Не удалось сделать поставку в магазин");
				throw;
			}
		}
	}
}
