using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;

namespace SecuritySystemDatabaseImplement.Implements
{
    public class ClientStorage : IClientStorage
    {
        public List<ClientViewModel> GetFullList()
        {
            using var context = new SecuritySystemDatabase();
            return context.Clients.Select(x => x.GetViewModel).ToList();
        }
        public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
        {
            using var context = new SecuritySystemDatabase();
            var clients = context.Clients       
            .Select(x => x.GetViewModel)
            .ToList();
            if (model.Id.HasValue)
            {
                clients = clients.Where(x => x.Id == model.Id.Value).ToList();
            }
            if (!model.Email.IsNullOrEmpty())
            {
                clients = clients.Where(x => x.Email == model.Email).ToList();
            }
            if (!model.Password.IsNullOrEmpty())
            {
                clients = clients.Where(x => x.Password == model.Password).ToList();
            }
            if (!model.ClientFIO.IsNullOrEmpty())
            {
                clients = clients.Where(x => x.ClientFIO == model.ClientFIO).ToList();
            }
            return clients;
        }
        public ClientViewModel? GetElement(ClientSearchModel model)
        {
            return GetFilteredList(model).FirstOrDefault();
        }
        public ClientViewModel? Insert(ClientBindingModel model)
        {
            var newClient = Client.Create(model);
            if (newClient == null)
            {
                return null;
            }
            using var context = new SecuritySystemDatabase();
            context.Clients.Add(newClient);
            context.SaveChanges();
            return newClient.GetViewModel;
        }
        public ClientViewModel? Update(ClientBindingModel model)
        {
            using var context = new SecuritySystemDatabase();
            var client = context.Clients.FirstOrDefault(x => x.Id == model.Id);
            if (client == null)
            {
                return null;
            }
            client.Update(model);
            context.SaveChanges();
            return client.GetViewModel;
        }
        public ClientViewModel? Delete(ClientBindingModel model)
        {
            using var context = new SecuritySystemDatabase();
            var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Clients.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
