DROP PROCEDURE IF EXISTS akuz.sp_rds_lloelectroniccertificate;

CREATE OR REPLACE PROCEDURE akuz.sp_rds_lloelectroniccertificate(
    "Xml" text DEFAULT NULL,
    "IsNew" boolean DEFAULT '1',
    "ID" uuid DEFAULT NULL::uuid,
    "QueueName" character varying DEFAULT 'rds.registry'::character varying,
    "dateTime" timestamp without time zone DEFAULT NULL::timestamp without time zone,
    "User" uuid DEFAULT NULL::uuid
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_id        uuid         := "ID";
    p_queuename varchar(128) := "QueueName";
    p_xml       xml          := "Xml";
    v_content   text;
BEGIN
    
    IF (p_xml IS NULL) THEN
        SELECT ap.signadata
        INTO v_content
        FROM akuz.t_llo_electronic_certificate_application ap
        WHERE ap.lloelectroniccertificateapplicationid = p_id;
        
        INSERT INTO
            akuz.t_rabbit_send_object (rabbitsendobjectid,
                                       queuename,
                                       messageid,
                                       headers,
                                       contentencoding,
                                       type,
                                       userid,
                                       createdatetime,
                                       ownerid,
                                       state,
                                       content)
        SELECT gen_random_uuid(),
               p_queuename,
               gen_random_uuid(),
               NULL,
               'utf-8',
               'LLO_ELECTRONIC_CERTIFICATE_APPLICATION',
               NULL,
               CURRENT_TIMESTAMP,
               p_id,
               0,
               public.converttexttobinaryzip(v_content, '')
        FROM akuz.t_rds_synchronization_config;
    ELSE
        CREATE TEMP TABLE temp AS
            SELECT (XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION/ApplicationDate/text()', x))[1]::timestamp AS applicationdate,
                   (XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION/Serial/text()', x))[1]::varchar(128)       AS serial,
                   (XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION/Number/text()', x))[1]::varchar(128)       AS number,
                   (XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION/Status/text()', x))[1]::integer            AS status,
                   (XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION/RecipeID/text()', x))[1]::uuid             AS recipeid
            FROM UNNEST(XPATH('/ELECTRONIC_CERTIFICATE_APPLICATION', p_xml)) AS x;
        
        UPDATE akuz.t_llo_electronic_certificate_application ap
        SET status = CASE t.status WHEN 1 THEN 1 WHEN 2 THEN 3 END
        FROM temp t
        WHERE ap.recipegeneral = t.recipeid;
    
    END IF;

END;
$$

