--
-- 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_all_donau_instances();
CREATE FUNCTION merchant.select_all_donau_instances()
RETURNS TABLE(
  out_donau_instances_serial INT8,
  out_donau_url TEXT,
  out_charity_name TEXT,
  out_charity_pub_key BYTEA,
  out_charity_id INT8,
  out_charity_max_per_year merchant.taler_amount_currency,
  out_charity_receipts_to_date merchant.taler_amount_currency,
  out_current_year INT8,
  out_keys_json JSONB)
LANGUAGE plpgsql
AS $FN$
DECLARE
  rec RECORD;
  s TEXT;
  inner_rec RECORD;
BEGIN
  FOR rec
  IN
    SELECT merchant_serial
          ,merchant_pub
      FROM merchant.merchant_instances
  LOOP
    s := 'merchant_instance_' || rec.merchant_serial::TEXT;
    BEGIN
      FOR inner_rec
      IN
        EXECUTE format(
          'SELECT'
          '  di.donau_instances_serial AS dis'
          ' ,di.donau_url AS du'
          ' ,di.charity_name AS cn'
          ' ,di.charity_id AS ci'
          ' ,di.charity_max_per_year AS cmp'
          ' ,di.charity_receipts_to_date AS crt'
          ' ,di.current_year AS cy'
          ' ,dk.keys_json AS kj'
          ' FROM %I.merchant_donau_instances di'
          ' LEFT JOIN merchant.merchant_donau_keys dk'
          '   ON di.donau_url = dk.donau_url', s)
      LOOP
        out_donau_instances_serial := inner_rec.dis;
        out_donau_url := inner_rec.du;
        out_charity_name := inner_rec.cn;
        out_charity_pub_key := rec.merchant_pub;
        out_charity_id := inner_rec.ci;
        out_charity_max_per_year := inner_rec.cmp;
        out_charity_receipts_to_date := inner_rec.crt;
        out_current_year := inner_rec.cy;
        out_keys_json := inner_rec.kj;
        RETURN NEXT;
      END LOOP;
    EXCEPTION
      WHEN undefined_table
      THEN
        NULL;
    END;
  END LOOP;
END
$FN$;
COMMENT ON FUNCTION merchant.select_all_donau_instances()
  IS 'Returns all donau-instance configurations across every per-instance'
     ' schema, joined with merchant.merchant_donau_keys for the keys json'
     ' and with merchant.merchant_instances for the charity public key.';
