--
-- 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_do_insert_unclaim_signature;
CREATE FUNCTION merchant_do_insert_unclaim_signature (
  IN in_instance_id TEXT,
  IN in_order_id TEXT,
  IN in_nonce_str TEXT,
  IN in_notify_str TEXT,
  IN in_h_contract_terms BYTEA,
  IN in_nonce_sig BYTEA,
  OUT out_found BOOL)
LANGUAGE plpgsql
AS $$
DECLARE
  my_merchant_serial INT8;
  my_expiration_time INT8;
BEGIN

  SELECT merchant_serial
    INTO my_merchant_serial
    FROM merchant_instances
   WHERE merchant_id=in_instance_id;

  IF NOT FOUND
  THEN
    out_found = FALSE;
    RETURN;
  END IF;

  SELECT pay_deadline
    INTO my_expiration_time
    FROM merchant_contract_terms
    WHERE order_id=in_order_id
      AND merchant_serial = my_merchant_serial
      AND contract_terms->>'nonce' = in_nonce_str;

  IF NOT FOUND
  THEN
    out_found = FALSE;
    RETURN;
  END IF;

  INSERT INTO merchant_unclaim_signatures
    (h_contract_terms
    ,unclaim_sig
    ,expiration_time)
    VALUES
    (in_h_contract_terms
    ,in_nonce_sig
    ,my_expiration_time)
    ON CONFLICT DO NOTHING:

  IF FOUND
  THEN
    out_found = TRUE;

    -- order status change notification
    EXECUTE FORMAT (
      'NOTIFY %s'
     ,in_notify_str);

    RETURN;
  END IF;

  PERFORM FROM merchant_unclaim_signatures
    WHERE h_contract_terms = in_h_contract_terms
      AND unclaim_sig = in_nonce_sig;
  out_found = FOUND;

END $$;
