--
-- This file is part of TALER
-- Copyright (C) 2025 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 do_insert_charity;
CREATE FUNCTION do_insert_charity (
   IN in_charity_pub BYTEA
  ,IN in_charity_name TEXT
  ,IN in_charity_url TEXT
  ,IN in_max_per_year taler_amount
  ,IN in_current_year INT4
  ,OUT out_charity_id INT8
)
LANGUAGE plpgsql
AS $$
BEGIN
  INSERT INTO charities
    (charity_pub
    ,charity_name
    ,charity_url
    ,max_per_year
    ,current_year
   ) VALUES (
    in_charity_pub
   ,in_charity_name
   ,in_charity_url
   ,in_max_per_year
   ,in_current_year)
   ON CONFLICT DO NOTHING
   RETURNING charity_id
        INTO out_charity_id;
  IF NOT FOUND
  THEN
    SELECT charity_id
      INTO out_charity_id
      FROM charities
     WHERE charity_pub=in_charity_pub
       AND charity_url=in_charity_url
       AND charity_name=in_charity_name
       AND max_per_year=in_max_per_year;
   IF NOT FOUND
   THEN
     out_charity_id = 0;
   END IF;
 END IF;
END $$;
COMMIT;

COMMENT ON FUNCTION do_insert_charity
  IS 'Insert a charity. Also succeeds if a charity with the same parameters already exists. If a conflicting charity exists, the out_charity_id is set to 0.';
