using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Implements;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ComputerShopRestApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EquipmentReceivingController : Controller
    {
        private readonly ILogger _logger;
        private readonly IEquipmentReceivingLogic _equipmentReceiving;
		private readonly IEquipmentReceivingStorage _equipmentReceivingStorage;
		public EquipmentReceivingController(ILogger<MainController> logger, IEquipmentReceivingLogic equipmentReceiving, IEquipmentReceivingStorage equipmentReceivingStorage)
        {
            _logger = logger;
            _equipmentReceiving = equipmentReceiving;
			_equipmentReceivingStorage = equipmentReceivingStorage;

		}
      
        [HttpGet]
        public List<EquipmentReceivingViewModel>? GetReceivings(int clientId)
        {
            try
            {
                return _equipmentReceiving.ReadList(new EquipmentReceivingSearchModel
                { 
                    ClientId = clientId
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка получения списка получений клиента id ={ Id}", clientId);
                throw;
            }
        }

		[HttpPost]
		public void SetFinish(int id)
		{
			try
			{
				var receiving = _equipmentReceivingStorage.GetElement(new() { Id = id });
				EquipmentReceivingBindingModel model = new EquipmentReceivingBindingModel()
				{
					Id = id,
					ClientId = receiving.ClientId,
					DateImplement = receiving.DateImplement,
					Status = receiving.Status
				};
				_equipmentReceiving.Finish(model);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка изменения закупки");
				throw;
			}
		}

		[HttpPost]
        public void CreateReceiving(EquipmentReceivingBindingModel model)
        {
            try
            {
                _equipmentReceiving.Create(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка создания получения");
                throw;
            }
        }

		[HttpPost]
		public void DeleteReceiving(int id)
		{
			try
			{
				var receiving = _equipmentReceivingStorage.GetElement(new() { Id = id });
				_equipmentReceiving.Delete(new()
				{
					Id = id,
					ClientId = receiving.ClientId,
					DateImplement = receiving.DateImplement,
					Status = receiving.Status
				});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка удаления");
				throw;
			}
		}
	}
}
