-- Author: Hayden Hargreaves (hhargreaves2006@gmail.com)
-- Desc:   Create the recipe of the week stored procedure.
-- Date:   07/26/2025, 1/10/2026

CREATE OR REPLACE PROCEDURE calculate_recipe_of_the_week_procedure()
LANGUAGE plpgsql
AS $$
BEGIN
  -- Insert the highest-scoring recipe from the last 7 days into daily_top_recipes
  INSERT INTO RecipeOfTheWeek (RecipeId, Score, Created)
    SELECT
      e.Entity AS RecipeId,
      (
        -- Weights can be configured here
        SUM(CASE WHEN e.Type = 'viewed' THEN 1 ELSE 0 END) * 0.20 +
        SUM(CASE WHEN e.Type = 'made' THEN 1 ELSE 0 END) * 0.40 +
        SUM(CASE WHEN e.Type = 'liked' THEN 1 ELSE 0 END) * 0.30 +
        SUM(CASE WHEN e.Type = 'shared' THEN 1 ELSE 0 END) * 0.10
      ) AS Score,
      NOW()
    FROM
    Engagements e
    JOIN Recipes r
      ON r.Id = e.Entity
      AND r.Deleted = FALSE
    WHERE
      e.Created >= NOW() - INTERVAL '7 days'
      AND e.Entity IS NOT NULL
    GROUP BY e.Entity
    ORDER BY Score DESC
    LIMIT 1;

  RAISE NOTICE 'Successfully calculated and stored the top recipe for the day.';


  EXCEPTION
    WHEN NO_DATA_FOUND THEN
        -- Handle cases where no engagements are found in the last 7 days
        RAISE NOTICE 'No engagement data found for the last 7 days to calculate a top recipe.';
    WHEN OTHERS THEN
        -- Catch any other potential errors and re-raise them after logging
        RAISE EXCEPTION 'An error occurred during top recipe calculation: %', SQLERRM;
END;
$$;
