class RecipeSerializer < ApplicationSerializer
  def serialize
    {
        id: item.id,
        name: item.name,
        rating: item.rating,
        yields: item.yields,
        total_time: item.total_time,
        active_time: item.active_time,
        source: item.source,
        is_ingredient: item.is_ingredient,
        created_at: item.created_at,
        updated_at: item.updated_at,
        step_text: item.step_text,
        converted_scale: item.converted_scale,
        converted_system: item.converted_system,
        converted_unit: item.converted_unit,

        rendered_steps: MarkdownProcessor.render(item.step_text),
        
        tags: item.tag_names,

        ingredients: item.recipe_ingredients.map do |ri|
          {
              id: ri.id,
              ingredient_id: ri.ingredient_id,
              display_name: ri.display_name,
              name: ri.name,
              quantity: ri.quantity,
              units: ri.units,
              preparation: ri.preparation,
              sort_order: ri.sort_order,

              ingredient: serialize_ingredient(ri),

              _destroy: false
          }
        end,

        nutrition_data: {
            errors: item.nutrition_data.errors,
            nutrients: NutritionData::NUTRIENTS.select { |_, v| v.present? }.map do |name, label|
              {
                  name: name,
                  label: label,
                  value: item.nutrition_data.send(name)
              }
            end
        }
    }
  end

  def serialize_ingredient(ri)
    if ri.food.nil? && ri.recipe_as_ingredient.nil?
      nil
    elsif ri.food
      {
          name: ri.food.name,
          density: ri.food.density,
          notes: ri.food.notes
      }
    else
      {
          name: ri.recipe_as_ingredient.name
      }
    end
  end

end