package app.mealsmadeeasy.api.recipe.converter;

import app.mealsmadeeasy.api.image.converter.ImageToViewConverter;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeService;
import app.mealsmadeeasy.api.recipe.view.FullRecipeView;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.view.UserInfoView;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class RecipeToFullViewConverter {

    private final RecipeService recipeService;
    private final ImageToViewConverter imageToViewConverter;

    public FullRecipeView convert(Recipe recipe, boolean includeRawText, @Nullable User viewer) {
        final var b = FullRecipeView.builder()
                .id(recipe.getId())
                .created(recipe.getCreated())
                .modified(recipe.getModified())
                .slug(recipe.getSlug())
                .title(recipe.getTitle())
                .preparationTime(recipe.getPreparationTime())
                .cookingTime(recipe.getCookingTime())
                .totalTime(recipe.getTotalTime())
                .text(this.recipeService.getRenderedMarkdown(recipe))
                .owner(UserInfoView.from(recipe.getOwner()))
                .starCount(this.recipeService.getStarCount(recipe))
                .viewerCount(this.recipeService.getViewerCount(recipe))
                .isPublic(recipe.getIsPublic());

        if (recipe.getIngredients() != null) {
            b.ingredients(recipe.getIngredients().stream()
                    .map(ingredient -> FullRecipeView.IngredientView.builder()
                            .amount(ingredient.getAmount())
                            .name(ingredient.getName())
                            .notes(ingredient.getNotes())
                            .build())
                    .toList()
            );
        }

        if (recipe.getMainImage() != null) {
            b.mainImage(this.imageToViewConverter.convert(recipe.getMainImage(), viewer, false));
        }

        if (includeRawText) {
            b.rawText(recipe.getRawText());
        }

        return b.build();
    }

}
