using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfectioneryDatabaseImplement.Implements
{
    public class MessageInfoStorage : IMessageInfoStorage
    {
        public List<MessageInfoViewModel> GetFullList()
        {
            using var context = new ConfectioneryDatabase();
            return context.MessagesInfo
                .Select(x => x.GetViewModel)
                .ToList();
        }
        public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
        {
            if (!model.ClientId.HasValue)
            {
                return new();
            }

            using var context = new ConfectioneryDatabase();
            return context.MessagesInfo
                .Where(x => x.ClientId == model.ClientId)
                .Select(x => x.GetViewModel)
                .ToList();
        }
        public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
        {
            if (string.IsNullOrEmpty(model.MessageId))
            {
                return null;
            }

            using var context = new ConfectioneryDatabase();
            return context.MessagesInfo
                .FirstOrDefault(x => x.MessageId == model.MessageId)
                ?.GetViewModel;
        }
        public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
        {
            var newMessage = MessageInfo.Create(model);
            if (newMessage == null)
            {
                return null;
            }

            using var context = new ConfectioneryDatabase();
            context.MessagesInfo.Add(newMessage);
            context.SaveChanges();
            return newMessage.GetViewModel;
        }
    }
}
