--
-- 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('libeufin-nexus-0011', NULL, NULL);

SET search_path TO libeufin_nexus;

ALTER TABLE outgoing_transactions
  ADD COLUMN acct_svcr_ref TEXT UNIQUE,
  ALTER COLUMN end_to_end_id DROP NOT NULL,
  ADD CONSTRAINT unique_id CHECK(COALESCE(end_to_end_id, acct_svcr_ref) IS NOT NULL);

ALTER TABLE incoming_transactions
  ADD COLUMN uetr UUID UNIQUE,
  ADD COLUMN tx_id TEXT UNIQUE,
  ADD COLUMN acct_svcr_ref TEXT UNIQUE;

UPDATE incoming_transactions SET 
  uetr = CASE WHEN bank_id ~ E'^[[:xdigit:]]{8}-([[:xdigit:]]{4}-){3}[[:xdigit:]]{12}$' THEN bank_id::uuid ELSE NULL END,
  tx_id = CASE WHEN bank_id ~ E'^[[:xdigit:]]{8}-([[:xdigit:]]{4}-){3}[[:xdigit:]]{12}$' THEN NULL ELSE bank_id END;

ALTER TABLE incoming_transactions
  DROP COLUMN bank_id,
  ALTER COLUMN subject DROP NOT NULL,
  ALTER COLUMN debit_payto DROP NOT NULL,
  ADD CONSTRAINT unique_id CHECK(COALESCE(uetr::text, tx_id, acct_svcr_ref) IS NOT NULL);

COMMIT;
