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

BEGIN;

SELECT _v.register_patch('libeufin-bank-0007', NULL, NULL);
SET search_path TO libeufin_bank;

-- Make customer not null
-- Fill missing name with an empty string. All accounts created using the API already 
-- have a non-null name, so this only applies to accounts created manually with SQL.
UPDATE customers SET name='' WHERE name is NULL;
ALTER TABLE customers ALTER COLUMN name SET NOT NULL;

-- Support all taler incoming transaction types
CREATE TYPE taler_incoming_type AS ENUM
  ('reserve' ,'kyc', 'wad');
ALTER TABLE taler_exchange_incoming 
  ADD type taler_incoming_type NOT NULL DEFAULT 'reserve',
  ADD account_pub BYTEA CHECK (LENGTH(account_pub)=32),
  ADD origin_exchange_url TEXT,
  ADD wad_id BYTEA CHECK (LENGTH(wad_id)=24),
  ALTER COLUMN reserve_pub DROP NOT NULL,
  ADD CONSTRAINT incoming_polymorphism CHECK(
    CASE type
      WHEN 'reserve' THEN reserve_pub IS NOT NULL AND account_pub IS NULL AND origin_exchange_url IS NULL AND wad_id IS NULL
      WHEN 'kyc' THEN reserve_pub IS NULL AND account_pub IS NOT NULL AND origin_exchange_url IS NULL AND wad_id IS NULL
      WHEN 'wad' THEN reserve_pub IS NULL AND account_pub IS NULL AND origin_exchange_url IS NOT NULL AND wad_id IS NOT NULL
    END
  );
ALTER TABLE taler_exchange_incoming ALTER COLUMN type DROP DEFAULT;
COMMIT;
