--
-- 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 merchant_do_update_money_pot;
CREATE FUNCTION merchant_do_update_money_pot (
  IN in_instance_id TEXT,
  IN in_money_pot_serial INT8,
  IN in_name TEXT,
  IN in_description TEXT,
  IN in_old_totals taler_amount_currency[], -- can be NULL!
  IN in_new_totals taler_amount_currency[], -- can be NULL!
  OUT out_conflict_total BOOL,
  OUT out_conflict_name BOOL,
  OUT out_not_found BOOL)
LANGUAGE plpgsql
AS $$
DECLARE
  my_merchant_id INT8;
BEGIN

SELECT merchant_serial
  INTO my_merchant_id
  FROM merchant_instances
  WHERE merchant_id=in_instance_id;

IF NOT FOUND
THEN
  -- If instance does not exist, pot cannot exist
  out_conflict_total = FALSE;
  out_conflict_name = FALSE;
  out_not_found = TRUE;
  RETURN;
END IF;

BEGIN
  UPDATE merchant_money_pots SET
    money_pot_name=in_name
   ,money_pot_description=in_description
   ,pot_totals=COALESCE(in_new_totals, pot_totals)
   WHERE merchant_serial=my_merchant_id
     AND money_pot_serial=in_money_pot_serial
     AND ( (in_old_totals IS NULL) OR (pot_totals=in_old_totals) );
  IF NOT FOUND
  THEN
    -- Check if pot_total was the problem
    PERFORM FROM merchant_money_pots
           WHERE merchant_serial=my_merchant_id
             AND money_pot_serial=in_money_pot_serial;
    out_conflict_total = FOUND;
    out_not_found = NOT FOUND;
    out_conflict_name = FALSE;
  ELSE
    out_conflict_total = FALSE;
    out_not_found = FALSE;
    out_conflict_name = FALSE;
  END IF;
  RETURN;
EXCEPTION
  -- money_pot_name already used
  WHEN unique_violation
  THEN
    out_conflict_name = TRUE;
    out_conflict_total = FALSE;
    out_not_found = FALSE;
    RETURN;
END;

END $$;
