--
-- 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_account_trigger.sql
-- @brief Run on INSERT/DELETE/UPDATE of accounts to generate report
-- @author Christian Grothoff


CREATE OR REPLACE FUNCTION merchant_account_change_trigger()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  IF TG_OP = 'DELETE'
  THEN
    -- The row is already gone, merchant_send_account_notification()
    -- could no longer resolve the account.
    RETURN NULL;
  END IF;
  -- Note: on INSERT the OLD record is NULL, so a newly added account
  -- is reported as a change as well.
  IF (OLD.payto_uri
     ,OLD.active)
  IS DISTINCT FROM
     (NEW.payto_uri
     ,NEW.active)
  THEN
    CALL merchant_send_account_notification(NEW.account_serial);
  END IF;
  RETURN NULL;
END $$;
