--
-- 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_send_account_notification.sql
-- @brief Send notification to merchant about new account status
-- @author Christian Grothoff


DROP PROCEDURE IF EXISTS merchant_send_account_notification;
CREATE PROCEDURE merchant_send_account_notification(
    in_account_serial INT8
  )
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 SUBSTRING(current_schema()::TEXT
                   FROM 'merchant_instance_([0-9]+)')::INT8
    INTO my_instance_serial;
  SELECT h_wire
    INTO my_h_wire
    FROM merchant_accounts
   WHERE account_serial=in_account_serial;
  IF NOT FOUND
  THEN
    RAISE WARNING 'Account not found, account change notification not triggered';
    RETURN;
  END IF;
  SELECT email
        ,notification_language
    INTO my_email
        ,my_notification_language
    FROM merchant.merchant_instances
    WHERE merchant_serial=my_instance_serial;
  IF NOT FOUND
  THEN
    RAISE WARNING 'Instance not found, account change notification not triggered';
    RETURN;
  END IF;
  IF my_notification_language IS NULL
  THEN
    -- Disabled
    RETURN;
  END IF;
  IF my_email IS NULL
  THEN
    -- Note: we MAY want to consider sending an SMS instead...
    RETURN;
  END IF;

  my_report_token = merchant.random_bytea(32);
  INSERT INTO merchant_reports (
    report_program_section
   ,report_description
   ,mime_type
   ,report_token
   ,data_source
   ,target_address
   ,frequency
   ,frequency_shift
   ,next_transmission
   ,one_shot_hidden
  ) VALUES (
    'email'
   ,'automatically triggered account change alert'
   ,'text/plain'
   ,my_report_token
   ,'/private/accounts/' || merchant.base32_crockford (my_h_wire)
   ,my_email
   ,0
   ,0
   ,0
   ,TRUE
  );
  -- Notify taler-merchant-report-generator
  NOTIFY XSSAB8NCBQR1K2VK7H2M6SMY3V5TNJT1C3BW0SN4F2QV0KHR3PRB0;
END $$;
