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

SET search_path TO libeufin_bank;

-- Cashout request UID need to be null for code triggered cashouts
ALTER TABLE cashout_operations DROP CONSTRAINT cashout_operations_pkey;
ALTER TABLE cashout_operations ADD CONSTRAINT request_uid_unique UNIQUE (request_uid);
ALTER TABLE cashout_operations ALTER COLUMN request_uid DROP NOT NULL;

-- Allow user accounts to have many tan channels
ALTER TABLE customers
  ADD COLUMN tan_channels tan_enum[] NOT NULL DEFAULT ARRAY[]::tan_enum[];
UPDATE customers 
  SET tan_channels = ARRAY[tan_channel]
  WHERE tan_channel IS NOT NULL;
ALTER TABLE customers DROP COLUMN tan_channel;

-- Only store salted body hash in challenges
TRUNCATE TABLE tan_challenges;
ALTER TABLE tan_challenges 
  DROP COLUMN body, 
  ADD COLUMN uuid UUID NOT NULL,
  ADD COLUMN hbody BYTEA NOT NULL CHECK (LENGTH(hbody)=64),
  ADD COLUMN salt BYTEA NOT NULL CHECK (LENGTH(salt)=16),
  ALTER COLUMN tan_channel SET NOT NULL,
  ALTER COLUMN tan_info SET NOT NULL;
COMMENT ON COLUMN tan_challenges.hbody
  IS 'Salted hash of the body of the original request that triggered the challenge, to be replayed once the challenge is satisfied.';
COMMENT ON COLUMN tan_challenges.salt
  IS 'Salt used when hashing the original body.';

CREATE INDEX tan_challenges_uuid_index ON tan_challenges (uuid);

-- Add new token scope 'observability'
ALTER TYPE token_scope_enum ADD VALUE 'observability';

COMMIT;
