using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZooContracts.BindingModels;
using ZooContracts.BusinessLogicsContracts;
using ZooContracts.SearchModel;
using ZooContracts.StoragesContracts;
using ZooContracts.ViewModels;
using ZooDatabaseImplements.Implements;


namespace ZooBusinessLogic.BusinessLogics
{
    public class ClientLogic : IClientLogic
    {
        private readonly ILogger _logger;
        private readonly IClientStorage _clientStorage;
        public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
        {
            _logger = logger;
            _clientStorage = clientStorage;
        }
        public bool Create(ClientBindingModel model)
        {
            CheckModel(model);
            if (_clientStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }

        public bool Delete(ClientBindingModel model)
        {
            CheckModel(model, false);
            _logger.LogInformation("Delete. Id: {Id}", model.Id);
            if (_clientStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");
                return false;
            }
            return true;
        }

        public ClientViewModel? ReadElement(ClientSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            _logger.LogInformation("ReadElement. Id: {Id}", model.Id);
            var element = _clientStorage.GetElement(model);
            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }
            _logger.LogInformation("ReadElement found. Id: {Id}", element.Id);
            return element;
        }

        public List<ClientViewModel>? ReadList(ClientSearchModel? model)
        {
            _logger.LogInformation("ReadList. Id: {Id}", model?.Id);
            var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
            if (list == null)
            {
                _logger.LogWarning("ReadList return null list");
                return null;
            }
            _logger.LogInformation("ReadList. Count: {Count}", list.Count);
            return list;
        }

        public bool Update(ClientBindingModel model)
        {
            CheckModel(model);
            if (_clientStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }
        private void CheckModel(ClientBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (string.IsNullOrEmpty(model.ClientEmail))
            {
                _logger.LogWarning("Email is empty");
                throw new ArgumentException("Не введён email");
            }
            if (model.ClientEmail.Length > 35)
            {
                _logger.LogWarning("Email {Email} length > 35", model.ClientEmail);
                throw new ArgumentException("Длина email не должна превышать 35 символов");
            }
            var existingClient = _clientStorage.GetElement(new()
            {
                ClientEmail = model.ClientEmail
            });
            if (existingClient != null)
            {
                _logger.LogWarning("Client with email {Email} already exists", model.ClientEmail);
                throw new ArgumentException("Клиент с таким email уже существует");
            }
            if (string.IsNullOrEmpty(model.ClientPassword))
            {
                _logger.LogWarning("Password is empty");
                throw new ArgumentException("Не введён пароль");
            }
            if (model.ClientPassword.Length < 7 || model.ClientPassword.Length > 30)
            {
                _logger.LogWarning("Password {Password} length > 30 or < 7", model.ClientPassword);
                throw new ArgumentException("Длина пароля должна быть в промежутке между 7 и 30 символами");
            }
            if (string.IsNullOrEmpty(model.ClientName))
            {
                _logger.LogWarning("Name is empty");
                throw new ArgumentException("Не введёно имя");
            }
            if (model.ClientName.Length > 30)
            {
                _logger.LogWarning("Name {Name} length > 30", model.ClientName);
                throw new ArgumentException("Длина имени не должна превышать 30 символов");
            }
            if (string.IsNullOrEmpty(model.ClientPhone))
            {
                _logger.LogWarning("Phone is empty");
                throw new ArgumentException("Не введён телефон");
            }
            if (model.ClientPhone.Length == 11)
            {
                _logger.LogWarning("Phone {Phone} length == 11", model.ClientPhone);
                throw new ArgumentException("Длина телефона  должна быть 11 символов");
            }
            _logger.LogInformation("Client. Id: {Id}", model.Id);
        }
    }
}
