package app.mealsmadeeasy.api.recipe.converter;

import app.mealsmadeeasy.api.image.Image;
import app.mealsmadeeasy.api.image.ImageService;
import app.mealsmadeeasy.api.recipe.body.RecipeDraftUpdateBody;
import app.mealsmadeeasy.api.recipe.spec.RecipeDraftUpdateSpec;
import app.mealsmadeeasy.api.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class RecipeDraftUpdateBodyToSpecConverter {

    private final ImageService imageService;

    public RecipeDraftUpdateSpec convert(RecipeDraftUpdateBody body, User viewer) {
        final var b = RecipeDraftUpdateSpec.builder()
                .slug(body.slug())
                .title(body.title())
                .preparationTime(body.preparationTime())
                .cookingTime(body.cookingTime())
                .totalTime(body.totalTime())
                .rawText(body.rawText());
        if (body.ingredients() != null) {
            final var ingredients = body.ingredients().stream()
                    .map(ingredientBody -> RecipeDraftUpdateSpec.IngredientDraftUpdateSpec.builder()
                            .amount(ingredientBody.amount())
                            .name(ingredientBody.name())
                            .notes(ingredientBody.notes())
                            .build()
                    ).toList();
            b.ingredients(ingredients);
        }
        if (body.mainImage() != null) {
            final Image mainImage = this.imageService.getByUsernameAndFilename(
                    body.mainImage().username(),
                    body.mainImage().userFilename(),
                    viewer
            );
            b.mainImage(mainImage);
        }
        return b.build();
    }
}
