--
-- This file is part of TALER
-- Copyright (C) 2024 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_account_kyc_set_failed;

CREATE FUNCTION merchant_do_account_kyc_set_failed (
  IN in_merchant_id TEXT,
  IN in_h_wire BYTEA,
  IN in_exchange_url TEXT,
  IN in_timestamp INT8,
  IN in_exchange_http_status INT4,
  IN in_kyc_ok BOOL,
  IN in_notify_str TEXT,
  IN in_notify2_str TEXT,
  OUT out_no_instance BOOL,
  OUT out_no_account BOOL)
LANGUAGE plpgsql
AS $$
DECLARE
  my_merchant_id INT8;
  my_account_serial INT8;
BEGIN

out_no_instance=FALSE;
out_no_account=FALSE;

-- Which instance are we using?
SELECT merchant_serial
  INTO my_merchant_id
  FROM merchant_instances
 WHERE merchant_id=in_merchant_id;

IF NOT FOUND
THEN
  out_no_instance=TRUE;
  RETURN;
END IF;

SELECT account_serial
  INTO my_account_serial
  FROM merchant_accounts
 WHERE merchant_serial=my_merchant_id
   AND h_wire=in_h_wire;

IF NOT FOUND
THEN
  out_no_account=TRUE;
  RETURN;
END IF;

UPDATE merchant_kyc
   SET kyc_timestamp=in_timestamp
      ,kyc_ok=in_kyc_ok
      ,exchange_http_status=in_exchange_http_status
      ,exchange_ec_code=0
 WHERE account_serial=my_account_serial
   AND exchange_url=in_exchange_url;

IF NOT FOUND
THEN

  INSERT INTO merchant_kyc
    (kyc_timestamp
    ,kyc_ok
    ,account_serial
    ,exchange_url
    ,exchange_http_status)
  VALUES
    (in_timestamp
    ,in_kyc_ok
    ,my_account_serial
    ,in_exchange_url
    ,in_exchange_http_status);
END IF;

EXECUTE FORMAT (
   'NOTIFY %s'
  ,in_notify_str);

EXECUTE FORMAT (
   'NOTIFY %s'
  ,in_notify2_str);


-- Success!
END $$;
