using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;

namespace SushiBarDatabaseImplement.Implements;

public class ClientStorage : IClientStorage
{
    public List<ClientViewModel> GetFullList()
    {
        using var context = new SushiBarDatabase();

        return context.Clients
            .Select(x => x.GetViewModel)
            .ToList();
    }

    public List<ClientViewModel> GetFilteredList(ClientSearchModel? model)
    {
        if (string.IsNullOrEmpty(model?.Email) ||
            string.IsNullOrEmpty(model.ClientFio))
        {
            return new List<ClientViewModel>();
        }
        
        using var context = new SushiBarDatabase();

        if (string.IsNullOrEmpty(model.Email))
        {
            return context.Clients
                .Where(x => x.Email.Equals(model.Email))
                .Select(x => x.GetViewModel)
                .ToList();
        }
        return context.Clients
            .Where(x => x.ClientFio.Equals(model.ClientFio))
            .Select(x => x.GetViewModel)
            .ToList();
    }

    public ClientViewModel? GetElement(ClientSearchModel model)
    {
        if (!model.Id.HasValue && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))
            return null;

        using var context = new SushiBarDatabase();
        
        if (model.Id.HasValue)
        {
            return context.Clients
                .FirstOrDefault(x => x.Id == model.Id)
                ?.GetViewModel;
        }

        return context.Clients
            .FirstOrDefault(x => x.Email == model.Email && x.Password == model.Password)
            ?.GetViewModel;
    }

    public ClientViewModel? Insert(ClientBindingModel model)
    {
        var newClient = Client.Create(model);
        if (newClient == null)
            return null;

        using var context = new SushiBarDatabase();
        context.Clients.Add(newClient);
        context.SaveChanges();

        return newClient.GetViewModel;
    }

    public ClientViewModel? Update(ClientBindingModel model)
    {
        using var context = new SushiBarDatabase();

        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 SushiBarDatabase();

        var client = context.Clients.FirstOrDefault(x => x.Id == model.Id);

        if (client != null)
        {
            context.Clients.Remove(client);
            context.SaveChanges();

            return client.GetViewModel;
        }

        return null;
    }
}