package app.mealsmadeeasy.api;

import app.mealsmadeeasy.api.job.JobService;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeRepository;
import app.mealsmadeeasy.api.recipe.RecipeSummary;
import app.mealsmadeeasy.api.recipe.job.RecipeSummaryJobHandler;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "backfill.recipe-embeddings.enabled", havingValue = "true")
public class BackfillRecipeEmbeddings implements ApplicationRunner {

    private final RecipeRepository recipeRepository;
    private final JobService jobService;

    @Override
    public void run(ApplicationArguments args) {
        final List<Recipe> recipeEntities = this.recipeRepository.findAll();
        for (final Recipe recipe : recipeEntities) {
            final @Nullable RecipeSummary summary = recipe.getSummary();
            if (summary == null || summary.getSummary() == null || summary.getEmbedding() == null) {
                this.jobService.create(
                        RecipeSummaryJobHandler.JOB_KEY,
                        new RecipeSummaryJobHandler.RecipeSummaryJobPayload(recipe.getId())
                );
            }
        }
    }

}
