using FishFactoryContracts.BindingModels;
using FishFactoryContracts.SearchModels;
using FishFactoryContracts.StoragesContracts;
using FishFactoryContracts.ViewModels;
using FishFactoryDatabaseImplement.Models;

namespace FishFactoryDatabaseImplement.Implements
{
    public class IngredientStorage : IIngredientStorage
    {
        public List<IngredientViewModel> GetFullList()
        {
            using var context = new FishFactoryDatabase();
            return context.Ingredients
                    .Select(x => x.GetViewModel)
                    .ToList();
        }

        public List<IngredientViewModel> GetFilteredList(IngredientSearchModel model)
        {
            if (string.IsNullOrEmpty(model.IngredientName))
            {
                return new();
            }
            using var context = new FishFactoryDatabase();
            return context.Ingredients
                    .Where(x => x.IngredientName.Contains(model.IngredientName))
                    .Select(x => x.GetViewModel)
                    .ToList();
        }

        public IngredientViewModel? GetElement(IngredientSearchModel model)
        {
            if (string.IsNullOrEmpty(model.IngredientName) && !model.Id.HasValue)
            {
                return null;
            }
            using var context = new FishFactoryDatabase();
            return context.Ingredients
                    .FirstOrDefault(x => (!string.IsNullOrEmpty(model.IngredientName) && x.IngredientName == model.IngredientName) ||
                        (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public IngredientViewModel? Insert(IngredientBindingModel model)
        {
            var newIngredient = Ingredient.Create(model);
            if (newIngredient == null)
            {
                return null;
            }
            using var context = new FishFactoryDatabase();
            context.Ingredients.Add(newIngredient);
            context.SaveChanges();
            return newIngredient.GetViewModel;
        }

        public IngredientViewModel? Update(IngredientBindingModel model)
        {
            using var context = new FishFactoryDatabase();
            var ingredient = context.Ingredients.FirstOrDefault(x => x.Id == model.Id);
            if (ingredient == null)
            {
                return null;
            }
            ingredient.Update(model);
            context.SaveChanges();
            return ingredient.GetViewModel;
        }

        public IngredientViewModel? Delete(IngredientBindingModel model)
        {
            using var context = new FishFactoryDatabase();
            var element = context.Ingredients.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Ingredients.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
