--
-- 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-0005', NULL, NULL);

SET search_path TO exchange;

-- convert all JSON-valued fields from TEXT to JSONB

CREATE FUNCTION alter_table_wire_accounts5()
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
  ALTER TABLE wire_accounts
    ALTER COLUMN debit_restrictions
      TYPE JSONB
      USING debit_restrictions::JSONB,
    ALTER COLUMN credit_restrictions
      TYPE JSONB
      USING credit_restrictions::JSONB;
END
$$;


CREATE FUNCTION alter_table_legitimization_outcomes5()
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
  ALTER TABLE legitimization_outcomes
    ALTER COLUMN jproperties
      TYPE JSONB
      USING jproperties::JSONB,
    ALTER COLUMN jnew_rules
      TYPE JSONB
      USING jnew_rules::JSONB;
END
$$;


CREATE FUNCTION alter_table_legitimization_measures5()
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
  ALTER TABLE legitimization_measures
    ALTER COLUMN jmeasures
      TYPE JSONB
      USING jmeasures::JSONB;
END
$$;


CREATE FUNCTION alter_table_policy_fulfillments5()
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
  ALTER TABLE policy_fulfillments
    ALTER COLUMN fulfillment_proof
      TYPE JSONB
      USING fulfillment_proof::JSONB;
END
$$;


CREATE FUNCTION alter_table_kyc_targets5()
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'kyc_targets';
BEGIN
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD COLUMN  open_time INT8 DEFAULT(NULL)'
    ',ADD COLUMN close_time INT8 DEFAULT(NULL);'
  );
END
$$;


INSERT INTO exchange_tables
    (name
    ,version
    ,action
    ,partitioned
    ,by_range)
  VALUES
    ('wire_accounts5'
    ,'exchange-0005'
    ,'alter'
    ,TRUE
    ,FALSE),
    ('legitimization_outcomes5'
    ,'exchange-0005'
    ,'alter'
    ,TRUE
    ,FALSE),
    ('legitimization_measures5'
    ,'exchange-0005'
    ,'alter'
    ,TRUE
    ,FALSE),
    ('policy_fulfillments5'
    ,'exchange-0005'
    ,'alter'
    ,TRUE
    ,FALSE),
    ('kyc_targets5'
    ,'exchange-0005'
    ,'alter'
    ,TRUE
    ,FALSE);


COMMIT;
