DROP PROCEDURE IF EXISTS aps.sp_updaterecipelastsignature;

CREATE OR REPLACE PROCEDURE aps.sp_updaterecipelastsignature(
    recipeid uuid
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_recipeid uuid := recipeid;
BEGIN
    
    WITH latestsignature AS
             (SELECT sig.savedate,
                     sig.recipe,
                     sig.recipesignatureid
              FROM aps.t_recipe_signature sig
              WHERE sig.recipe = p_recipeid
                AND NOT EXISTS (SELECT 1
                                FROM aps.t_recipe_signature sig2
                                WHERE sig2.recipe = sig.recipe
                                  AND sig2.savedate > sig.savedate
                               )
             )
    UPDATE aps.t_recipe r
    SET lastsignature = ls.recipesignatureid
    FROM latestsignature ls
    WHERE r.recipeid = ls.recipe;

END;
$$