using CarCenterContracts.BindingModels;
using CarCenterContracts.BusinessLogicsContracts;
using CarCenterContracts.SearchModels;
using CarCenterContracts.StoragesContracts;
using CarCenterContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

namespace CarCenterBusinessLogic.BusinessLogics
{
    public class ManagerLogic : IManagerLogic
    {
        private readonly int _loginMaxLength = 50;
        private readonly int _passwordMaxLength = 50;
        private readonly int _passwordMinLength = 10;

        private readonly ILogger _logger;
        private readonly IManagerStorage _managerStorage;

        public ManagerLogic(ILogger<ManagerLogic> logger, IManagerStorage ManagerStorage)
        {
            _logger = logger;
            _managerStorage = ManagerStorage;
        }

        public bool Create(ManagerBindingModel model)
        {
            CheckModel(model);

            if (_managerStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");

                return false;
            }

            return true;
        }

        public bool Delete(ManagerBindingModel model)
        {
            CheckModel(model, false);

            _logger.LogInformation("Delete. Id: {Id}", model.Id);

            if (_managerStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");

                return false;
            }

            return true;
        }

        public ManagerViewModel? ReadElement(ManagerSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            _logger.LogInformation("ReadElement. ManagerFIO: {ManagerFIO}. ManagerLogin: {ManagerLogin}. Id: {Id}.", model.ManagerFIO, model.ManagerLogin, model.Id);

            var element = _managerStorage.GetElement(model);

            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }

            _logger.LogInformation("ReadElement find. Id: {Id}", element.Id);

            return element;
        }

        public List<ManagerViewModel>? ReadList(ManagerSearchModel? model)
        {
            _logger.LogInformation("ReadList. ManagerFIO: {ManagerFIO}. ManagerLogin: {ManagerLogin}. Id: {Id}.", model?.ManagerFIO, model?.ManagerLogin, model?.Id);

            var list = model == null ? _managerStorage.GetFullList() : _managerStorage.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(ManagerBindingModel model)
        {
            CheckModel(model);

            if (_managerStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }

        private void CheckModel(ManagerBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!withParams)
            {
                return;
            }

            if (string.IsNullOrEmpty(model.ManagerFIO))
            {
                throw new ArgumentNullException("Нет ФИО менеджера", nameof(model.ManagerFIO));
            }

            if (string.IsNullOrEmpty(model.ManagerLogin))
            {
                throw new ArgumentNullException("Нет логина менеджера", nameof(model.ManagerLogin));
            }

            if (model.ManagerLogin.Length>_loginMaxLength)
            {
                throw new ArgumentNullException("Логин слишком длинный", nameof(model.ManagerLogin));
            }

            if (string.IsNullOrEmpty(model.ManagerNumber))
            {
                throw new ArgumentNullException("Нет номера телефона менеджера", nameof(model.ManagerNumber));
            }

            if (model.ManagerEmail.Length > _loginMaxLength || !Regex.IsMatch(model.ManagerEmail, @"([a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+)"))
            {
                throw new Exception($"В качестве логина должна быть указана почта и иметь длинну не более {_loginMaxLength} символов");
            }

            if (string.IsNullOrEmpty(model.ManagerEmail))
            {
                throw new ArgumentNullException("Нет почты менеджера", nameof(model.ManagerEmail));
            }

            if (string.IsNullOrEmpty(model.ManagerPassword))
            {
                throw new ArgumentNullException("Нет пароля менеджера", nameof(model.ManagerPassword));
            }

            if (model.ManagerPassword.Length > _passwordMaxLength || model.ManagerPassword.Length < _passwordMinLength
                || !Regex.IsMatch(model.ManagerPassword, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$"))
            {
                throw new Exception($"Пароль длиной от {_passwordMinLength} до {_passwordMaxLength} должен состоять из цифр, букв и небуквенных символов");
            }

            _logger.LogInformation("Manager. ManagerFIO: {ManagerFIO}. ManagerLogin: {ManagerLogin}. Id: {Id}", model.ManagerFIO, model.ManagerLogin, model.Id);

            var element = _managerStorage.GetElement(new ManagerSearchModel
            {
                ManagerEmail = model.ManagerEmail
            });

            if (element != null && element.Id != model.Id)
            {
                throw new InvalidOperationException("менеджер с таким логином уже есть");
            }
        }
    }
}
