--
-- This file is part of TALER
-- Copyright (C) 2026 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-0014', NULL, NULL);

SET search_path TO libeufin_nexus;
-- Drop unused index
DROP INDEX talerable_incoming_polymorphism;

-- Add outgoing transactions metadata field
ALTER TABLE transfer_operations ADD COLUMN metadata TEXT;
ALTER TABLE talerable_outgoing_transactions ADD COLUMN metadata TEXT;

-- Replace unused wad type with new mapping type
ALTER TYPE taler_incoming_type RENAME VALUE 'wad' TO 'map';

ALTER TABLE talerable_incoming_transactions
    ADD COLUMN authorization_pub BYTEA CHECK (LENGTH(authorization_pub)=32),
    ADD COLUMN authorization_sig BYTEA CHECK (LENGTH(authorization_sig)=64);

CREATE TABLE prepared_transfers (
    type taler_incoming_type NOT NULL,
    account_pub BYTEA NOT NULL CHECK (LENGTH(account_pub)=32),
    authorization_pub BYTEA UNIQUE NOT NULL CHECK (LENGTH(authorization_pub)=32),
    authorization_sig BYTEA NOT NULL CHECK (LENGTH(authorization_sig)=64),
    recurrent BOOLEAN NOT NULL,
    reference_number TEXT UNIQUE CHECK(reference_number ~ '^\d{27}$'),
    registered_at INT8 NOT NULL,
    incoming_transaction_id INT8 UNIQUE REFERENCES incoming_transactions(incoming_transaction_id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX prepared_transfers_unique_reserve_pub 
    ON prepared_transfers (account_pub) WHERE type = 'reserve';
CREATE INDEX prepared_transfers_timestamp
    ON prepared_transfers (registered_at);

CREATE TABLE pending_recurrent_incoming_transactions(
    incoming_transaction_id INT8 NOT NULL UNIQUE REFERENCES incoming_transactions(incoming_transaction_id) ON DELETE CASCADE,
    authorization_pub BYTEA NOT NULL REFERENCES prepared_transfers(authorization_pub)
);
CREATE INDEX pending_recurrent_incoming_transactions_auth_pub
    ON pending_recurrent_incoming_transactions (authorization_pub);


COMMIT;
