using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;

namespace SushiBarBusinessLogic
{
    public class MessageInfoLogic : IMessageInfoLogic
    {

        private readonly ILogger logger;
        private readonly IMessageInfoStorage messageStorage;
        private readonly IClientLogic clientLogic;

        public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageStorage, IClientLogic clientLogic)
        {
            this.logger = logger;
            this.messageStorage = messageStorage;
            this.clientLogic = clientLogic;
        }

        public bool Create(MessageInfoBindingModel model)
        {
            var message = messageStorage.GetElement(new MessageInfoSearchModel { MessageId = model.MessageId});
            if (message != null) return false;
            var client = clientLogic.ReadElement(new ClientSearchModel{ Email = model.SenderName });
            if (client != null)
            {
                model.ClientId = client.Id;
            }
            if (messageStorage.Insert(model) == null)
            {
                logger.LogWarning("Insert message operation failed");
                return false;
            }
            return true;
        }

        public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
        {
            var list = model == null ? messageStorage.GetFullList() : messageStorage.GetFilteredList(model);
            if (list == null)
            {
                logger.LogWarning("ReadList had returned a null list");
                return null;
            }
            logger.LogInformation($"ReadList. Count of elements: {list.Count}");
            return list;
        }
    }
}
