--
-- 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.create_instance_schema;
CREATE FUNCTION merchant.create_instance_schema(
  in_merchant_serial BIGINT
)
  RETURNS void
  LANGUAGE plpgsql
  AS $$
DECLARE
  s TEXT := 'merchant_instance_' || in_merchant_serial::TEXT;
  r RECORD;
BEGIN
  EXECUTE format('CREATE SCHEMA %I', s);

  -- Call fixup functions to initialize all tables
  FOR r IN
    SELECT migration_name
      FROM merchant.instance_fixups
     ORDER BY version ASC
  LOOP
    EXECUTE FORMAT ('CALL merchant.%I(%L)', r.migration_name, s);
  END LOOP;
  EXECUTE FORMAT ('CALL merchant.sync_instance_procedures(%s)', in_merchant_serial);
END $$;

COMMENT ON FUNCTION merchant.create_instance_schema(BIGINT)
  IS 'Constructs the per-instance schema merchant_instance_<merchant_serial>'
     ' with all per-instance tables, stored procedures and triggers.  Called from'
     ' merchant_instances_after_insert_trigger() whenever a new instance row'
     ' is inserted into merchant.merchant_instances.';
