--
-- This file is part of TALER
-- Copyright (C) 2025 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--

DROP FUNCTION IF EXISTS exchange_do_insert_sanction_list_hit;
CREATE FUNCTION exchange_do_insert_sanction_list_hit(
  IN in_h_normalized_payto BYTEA,
  IN in_decision_time INT8,
  IN in_expiration_time INT8,
  IN in_properties TEXT, -- can be NULL
  IN in_new_rules TEXT, -- can be NULL
  IN in_to_investigate BOOLEAN,
  IN in_notify_s TEXT,
  IN ina_events TEXT[],
  OUT out_outcome_serial_id INT8)
LANGUAGE plpgsql
AS $$
DECLARE
  my_i INT4;
  ini_event TEXT;
BEGIN

INSERT INTO legitimization_outcomes
  (h_payto
  ,decision_time
  ,expiration_time
  ,jproperties
  ,to_investigate
  ,jnew_rules
  )
  VALUES
  (in_h_normalized_payto
  ,in_decision_time
  ,in_expiration_time
  ,in_properties
  ,in_to_investigate
  ,in_new_rules
  )
  RETURNING
    outcome_serial_id
  INTO
    out_outcome_serial_id;

-- Trigger events
FOR i IN 1..COALESCE(array_length(ina_events,1),0)
LOOP
  ini_event = ina_events[i];
  INSERT INTO kyc_events
    (event_timestamp
    ,event_type)
    VALUES
    (in_decision_time
    ,ini_event);
END LOOP;

EXECUTE FORMAT (
   'NOTIFY %s'
  ,in_notify_s);


END $$;


COMMENT ON FUNCTION exchange_do_insert_sanction_list_hit(BYTEA, INT8, INT8, TEXT, TEXT, BOOLEAN, TEXT, TEXT[])
  IS 'Insert result from sanction list check into the table';
