--
-- 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 do_update_charity;
CREATE FUNCTION do_update_charity (
   IN in_charity_id INT8
  ,IN in_charity_pub BYTEA
  ,IN in_charity_name TEXT
  ,IN in_charity_url TEXT
  ,IN in_max_per_year taler_amount
  ,OUT out_found BOOLEAN
  ,OUT out_conflict BOOLEAN
)
LANGUAGE plpgsql
AS $$
BEGIN
  out_conflict = FALSE;
  UPDATE charities
     SET charity_pub=in_charity_pub
        ,charity_name=in_charity_name
        ,charity_url=in_charity_url
        ,max_per_year=in_max_per_year
   WHERE charity_id=in_charity_id;
  out_found = FOUND;
EXCEPTION
  WHEN unique_violation THEN
    -- charity_pub is the primary key of `charities' and is entirely
    -- client-supplied; a collision means "this key belongs to a different
    -- charity", NOT "no such charity_id".
    out_found = TRUE;
    out_conflict = TRUE;
END $$;

COMMENT ON FUNCTION do_update_charity
  IS 'Updates a charity. out_found is FALSE if no charity with the given charity_id exists; out_conflict is TRUE if the requested charity_pub is already used by another charity.';
