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

SET search_path TO libeufin_nexus;

-- Better polymorphism schema
ALTER TABLE talerable_incoming_transactions ADD COLUMN metadata BYTEA;
UPDATE talerable_incoming_transactions 
  SET metadata=COALESCE (reserve_public_key, account_pub, wad_id);
ALTER TABLE talerable_incoming_transactions
  DROP CONSTRAINT incoming_polymorphism,
  DROP COLUMN reserve_public_key,
  DROP COLUMN account_pub,
  DROP COLUMN wad_id,
  ALTER COLUMN metadata SET NOT NULL,
  ADD CONSTRAINT polymorphism CHECK(
    CASE type
      WHEN 'wad' THEN LENGTH(metadata)=24 AND origin_exchange_url IS NOT NULL
      ELSE LENGTH(metadata)=32 AND origin_exchange_url IS NULL
    END
  );
CREATE INDEX talerable_incoming_polymorphism ON talerable_incoming_transactions (type, metadata);
CREATE UNIQUE INDEX talerable_incoming_transactions_unique_reserve_pub ON talerable_incoming_transactions (metadata) WHERE type = 'reserve';

COMMIT;
