--
-- 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 merchant-0032.sql
-- @brief Add field for one-shot reports in the merchant_reports table
-- @author Christian Grothoff

BEGIN;

-- Check patch versioning is in place.
SELECT _v.register_patch('merchant-0032', NULL, NULL);

SET search_path TO merchant;

ALTER TABLE merchant_reports
  ADD COLUMN one_shot_hidden BOOL DEFAULT(FALSE);

COMMENT ON COLUMN merchant_reports.one_shot_hidden
  IS 'True for reports that are only supposed to trigger once and that should be hidden from the user interface as they are internally generated. Used for alerts, such as those generated when the KYC status changes.';


CREATE FUNCTION random_bytea(
  bytea_length INT
)
RETURNS BYTEA
  AS $body$
  SELECT decode(string_agg(lpad(to_hex(width_bucket(random(), 0, 1, 256)-1),2,'0') ,''), 'hex')
    FROM generate_series(1, $1);
  $body$
LANGUAGE 'sql'
VOLATILE;

COMMENT ON FUNCTION random_bytea(INT)
  IS 'Create BYTEA of the given length and fill it with random bytes';


CREATE FUNCTION merchant_kyc_insert_trigger()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  CALL merchant_send_kyc_notification(NEW.account_serial,
                                      NEW.exchange_url);
  RETURN NEW;
END $$;

CREATE FUNCTION merchant_kyc_update_trigger()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  CALL merchant_send_kyc_notification(NEW.account_serial,
                                      NEW.exchange_url);
  RETURN NEW;
END $$;

-- Whenever KYC status changes, call our trigger to generate a notification
CREATE TRIGGER merchant_kyc_on_insert
  AFTER INSERT
     ON merchant_kyc
  FOR EACH ROW EXECUTE FUNCTION merchant_kyc_insert_trigger();

CREATE TRIGGER merchant_kyc_on_update
  AFTER UPDATE
     ON merchant_kyc
  FOR EACH ROW EXECUTE FUNCTION merchant_kyc_update_trigger();


COMMIT;
