const { PrismaClient } = require("@prisma/client"); class recipeModel { constructor() { this.prisma = new PrismaClient(); } async getAllRecipes() { try { return await this.prisma.recipes.findMany(); } catch (err) { console.error("Error fetching all recipies:", err); throw new Error(err.message); } } async findById(id) { try { const recipe = await this.prisma.recipes.findUnique({ where: { id }, include: { recipeSteps: true, recipeIngredients: true }, }); if (!recipe) { return null; } const data = { details: { id: recipe.id, name: recipe.name, author: recipe.author, cuisine: recipe.cuisine, stars: recipe.stars, prep_minutes: recipe.prep_minutes, cook_minutes: recipe.cook_minutes, }, ingredients: recipe.recipeIngredients.map((ing) => ing.raw), steps: recipe.recipeSteps.map((step, idx) => ({ step_idx: step.step_number, instruction: step.instruction, })), }; return data; } catch (err) { console.error("Error finding recipe:", err); throw new Error(err.message); } } async addRecipe(recipeData) { const { name, author, cuisine, stars, ingredients, steps, prep_minutes, cook_minutes, } = recipeData; try { const createdRecipe = await this.prisma.recipes.create({ data: { name, author, cuisine, prep_minutes, cook_minutes, stars, recipeIngredients: { create: ingredients.map((ing) => ({ raw: ing })), }, recipeSteps: { create: Object.keys(steps).map((stepNumber) => ({ step_number: parseInt(stepNumber), instruction: steps[stepNumber], })), }, }, }); return createdRecipe; } catch (error) { console.log(error); throw new Error("Failed to add recipe"); } } async setStars(id, stars) { try { await this.prisma.recipes.update({ where: { id }, data: { stars }, }); return { message: "stars updated" }; } catch (err) { console.error("Error updating stars:", err); throw new Error(err.message); } } async deleteRecipe(id) { try { await this.prisma.recipe_ingredients.deleteMany({ where: { recipe_id: id }, // Ensure you have the right foreign key relation }); await this.prisma.recipe_steps.deleteMany({ where: { recipe_id: id }, // Ensure you have the right foreign key relation }); const deletedRecipe = await this.prisma.recipes.delete({ where: { id }, }); return { message: "Recipe deleted successfully" }; } catch (err) { console.error("Error deleting recipe:", err); throw new Error(err.message); } } } module.exports = recipeModel;