--
-- 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/>
--

DROP FUNCTION IF EXISTS merchant.merchant_instances_after_insert_trigger() CASCADE;
CREATE FUNCTION merchant.merchant_instances_after_insert_trigger()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
  PERFORM merchant.create_instance_schema(NEW.merchant_serial);
  RETURN NEW;
END $$;
COMMENT ON FUNCTION merchant.merchant_instances_after_insert_trigger()
  IS 'Builds the per-instance schema merchant_instance_<merchant_serial>'
     ' for the newly inserted row.';

DROP TRIGGER IF EXISTS merchant_instances_on_insert
  ON merchant.merchant_instances;
CREATE TRIGGER merchant_instances_on_insert
  AFTER INSERT
    ON merchant.merchant_instances
  FOR EACH ROW
  EXECUTE FUNCTION merchant.merchant_instances_after_insert_trigger();


DROP FUNCTION IF EXISTS merchant.merchant_instances_after_delete_trigger() CASCADE;
CREATE FUNCTION merchant.merchant_instances_after_delete_trigger()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
  EXECUTE format('DROP SCHEMA IF EXISTS %I CASCADE',
                 'merchant_instance_' || OLD.merchant_serial::TEXT);
  RETURN NULL;
END $$;
COMMENT ON FUNCTION merchant.merchant_instances_after_delete_trigger()
  IS 'Drops the per-instance schema merchant_instance_<merchant_serial>'
     ' when its row in merchant.merchant_instances is removed.';

DROP TRIGGER IF EXISTS merchant_instances_on_delete
  ON merchant.merchant_instances;
CREATE TRIGGER merchant_instances_on_delete
  AFTER DELETE ON merchant.merchant_instances
  FOR EACH ROW
  EXECUTE FUNCTION merchant.merchant_instances_after_delete_trigger();
