--
-- 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_delete_charity;
CREATE FUNCTION do_delete_charity (
   IN in_charity_id INT8
  ,OUT out_found BOOLEAN
  ,OUT out_in_use BOOLEAN
)
LANGUAGE plpgsql
AS $$
BEGIN
  out_in_use = FALSE;
  DELETE FROM charities
   WHERE charity_id=in_charity_id;
  out_found = FOUND;
EXCEPTION
  WHEN foreign_key_violation THEN
    -- receipts_issued references this charity with ON DELETE RESTRICT,
    -- because receipts_issued.receipt_hash is the idempotence key of
    -- POST /batch-issue and must outlive the charity row.
    out_found = TRUE;
    out_in_use = TRUE;
END $$;

COMMENT ON FUNCTION do_delete_charity
  IS 'Deletes a charity. out_found is FALSE if no charity with the given charity_id exists; out_in_use is TRUE if the charity still has issued receipts and was therefore NOT deleted.';
