--
-- 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.select_accounts;
CREATE FUNCTION merchant.select_accounts()
RETURNS TABLE(
  out_merchant_id TEXT,
  out_merchant_priv BYTEA,
  out_h_wire BYTEA,
  out_salt BYTEA,
  out_payto_uri TEXT,
  out_credit_facade_url TEXT,
  out_credit_facade_credentials JSONB,
  out_extra_wire_subject_metadata TEXT,
  out_active BOOLEAN)
LANGUAGE plpgsql
AS $$
DECLARE
  rec RECORD;
BEGIN
  FOR rec IN
    SELECT mi.merchant_serial
          ,mi.merchant_id
          ,mi.merchant_priv
      FROM merchant.merchant_instances mi
  LOOP
    BEGIN
      FOR out_h_wire,
          out_salt,
          out_payto_uri,
          out_credit_facade_url,
          out_credit_facade_credentials,
          out_extra_wire_subject_metadata,
          out_active
      IN EXECUTE format('SELECT'
                        ' h_wire'
                        ',salt'
                        ',payto_uri'
                        ',credit_facade_url'
                        ',credit_facade_credentials'
                        ',extra_wire_subject_metadata'
                        ',active'
                        ' FROM %I.merchant_accounts',
                        'merchant_instance_' || rec.merchant_serial::TEXT)
      LOOP
        out_merchant_id := rec.merchant_id;
        out_merchant_priv := rec.merchant_priv;
        RETURN NEXT;
      END LOOP;
    EXCEPTION
      WHEN undefined_table THEN
        NULL;
    END;
  END LOOP;
END $$;

COMMENT ON FUNCTION merchant.select_accounts()
  IS 'Returns one row per merchant_account across all (or one) instance schemas;'
     ' merchant_priv is read from merchant.merchant_instances (NULL if absent).'
     ' If in_merchant_id is non-NULL, only that instance is scanned.';
