--
-- 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/>
--

BEGIN;

SELECT _v.register_patch('exchange-0006', NULL, NULL);

SET search_path TO exchange;

CREATE PROCEDURE patch_table_kyc_targets()
LANGUAGE plpgsql
AS $$
DECLARE
  my_rec RECORD;
  my_payto TEXT;
  my_is_wallet BOOL;
  my_setup_extension BOOL;
  wtc CURSOR FOR
   SELECT
     h_normalized_payto
    ,payto_uri
     FROM exchange.wire_targets;
BEGIN

PERFORM
  FROM pg_tables
 WHERE schemaname = 'exchange'
   AND tablename  = 'wire_targets';
IF FOUND
THEN

  -- Fix any remaining NULL columns in wire_targets
  CREATE EXTENSION IF NOT EXISTS pgcrypto;
  my_setup_extension = FOUND;
  UPDATE wire_targets
       SET h_normalized_payto=substring(digest(convert_to(payto_uri, 'UTF8') || E'\\000'::bytea, 'sha512') FROM 1 FOR 32)
   WHERE h_normalized_payto IS NULL;
  IF my_setup_extension
  THEN
    DROP EXTENSION pgcrypto;
  END IF;
END IF;

-- Only run the migration if the tables already exist.
PERFORM
  FROM pg_tables
 WHERE schemaname = 'exchange'
   AND tablename  = 'kyc_targets';

IF FOUND
THEN

  FOR my_rec IN wtc
  LOOP
    my_payto = my_rec.payto_uri;
    my_is_wallet
      = (LOWER (SUBSTRING (my_payto, 0, 23)) =
         'payto://taler-reserve/') OR
        (LOWER (SUBSTRING (my_payto, 0, 28)) =
         'payto://taler-reserve-http/');
    UPDATE kyc_targets
      SET is_wallet=my_is_wallet
     WHERE h_normalized_payto=my_rec.h_normalized_payto;
  END LOOP;
END IF;

END $$;

CALL patch_table_kyc_targets();

DROP PROCEDURE patch_table_kyc_targets;

COMMIT;
