require 'rails_helper'

RSpec.describe RecipeIngredient, type: :model do

  describe 'to_mass' do

    it 'converts volume ingredients with density' do
      ri = RecipeIngredient.new(quantity: 2, units: 'tbsp', food: create(:food_with_density))
      ri.to_mass
      expect(ri.units).to eq 'ounce'
    end

    it 'converts ingredients with custom units' do
      i = create(:food_with_density)
      i.food_units << FoodUnit.new(name: 'pat', gram_weight: 25)
      ri = RecipeIngredient.new(quantity: 2, units: 'pat', food: i)
      ri.to_mass
      expect(ri.quantity).to eq '50'
      expect(ri.units).to eq 'gram'
    end

  end

  describe '#calculate_nutrition_ratio' do
    it 'returns nil if no ratio can be calculated' do
      ri = create(:recipe_ingredient)
      expect(ri.calculate_nutrition_ratio).to be_nil

      ri.quantity = 50
      expect(ri.calculate_nutrition_ratio).to be_nil

      ri.units = 'cats'
      expect(ri.calculate_nutrition_ratio).to be_nil
    end

    describe 'with recipe_as_ingredient' do
      let(:recipe) { create(:recipe, yields: '250 g, 0.5 l, 2 rolls') }
      let(:recipe_ingredient) { create(:recipe_ingredient, food: nil, recipe_as_ingredient: recipe) }

      it 'returns nil with no quantity' do
        ri = recipe_ingredient
        expect(ri.calculate_nutrition_ratio).to be_nil
      end

      it 'returns returns a proper scale with a unitless quantity' do
        ri = recipe_ingredient
        ri.quantity = 2
        expect(ri.calculate_nutrition_ratio).to eq 2

        ri.quantity = 4
        expect(ri.calculate_nutrition_ratio).to eq 4
      end

      it 'returns a proper scale with a counted unit' do
        ri = recipe_ingredient
        ri.quantity = 3
        ri.units = "rolls"
        expect(ri.calculate_nutrition_ratio).to eq 1.5
      end

      it 'returns a proper scale with a mass unit' do
        ri = recipe_ingredient
        ri.quantity = 500
        ri.units = 'g'
        expect(ri.calculate_nutrition_ratio).to eq 2
      end
    end

    describe 'with food' do
      let(:food) { create(:food) }
      let(:recipe_ingredient) { create(:recipe_ingredient, food: food) }

      it 'returns a proper scale with a mass unit' do
        ri = recipe_ingredient
        ri.quantity = 500
        ri.units = 'g'
        expect(ri.calculate_nutrition_ratio).to eq 5
      end
    end
  end

end
