--
-- This file is part of TALER
-- Copyright (C) 2026 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/>

-- @file pg_merchant_kyc_trigger.sql
-- @brief Fix trigger logic
-- @author Christian Grothoff



DROP PROCEDURE IF EXISTS merchant_send_kyc_notification;
CREATE PROCEDURE merchant_send_kyc_notification(
    in_account_serial INT8
   ,in_exchange_url TEXT
  )
LANGUAGE plpgsql
AS $$
DECLARE
  my_instance_serial INT8;
  my_report_token BYTEA;
  my_h_wire BYTEA;
  my_email TEXT;
  my_notification_language TEXT;
BEGIN
  SELECT merchant_serial
        ,h_wire
    INTO my_instance_serial
        ,my_h_wire
    FROM merchant_accounts
   WHERE account_serial=in_account_serial;
  IF NOT FOUND
  THEN
    RAISE WARNING 'Account not found, KYC change notification not triggered';
    RETURN;
  END IF;
  SELECT email
        ,notification_language
    INTO my_email
        ,my_notification_language
    FROM merchant_instances
    WHERE merchant_serial=my_instance_serial;
  IF NOT FOUND
  THEN
    RAISE WARNING 'Instance not found, KYC change notification not triggered';
    RETURN;
  END IF;
  IF my_notification_language IS NULL
  THEN
    -- Disabled
  END IF;
  IF my_email IS NULL
  THEN
    -- Note: we MAY want to consider sending an SMS instead...
    RETURN;
  END IF;

  my_report_token = random_bytea(32);
  INSERT INTO merchant_reports (
    merchant_serial
   ,report_program_section
   ,report_description
   ,mime_type
   ,report_token
   ,data_source
   ,target_address
   ,frequency
   ,frequency_shift
   ,next_transmission
   ,one_shot_hidden
  ) VALUES (
    my_instance_serial
   ,'email'
   ,'automatically triggered KYC alert'
   ,'text/plain'
   ,my_report_token
   ,'/private/kyc?exchange_url=' || uri_escape(in_exchange_url)
     || '&h_wire=' || base32_crockford (my_h_wire)
   ,my_email
   ,0
   ,0
   ,0
   ,TRUE
  );
  -- Notify taler-merchant-report-generator
  NOTIFY XSSAB8NCBQR1K2VK7H2M6SMY3V5TNJT1C3BW0SN4F2QV0KHR3PRB0;
END $$;
