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

-- @file merchant-0008.sql
-- @brief add merchant_issued_tokens table
-- @author Christian Blättler

-- Everything in one big transaction
BEGIN;

-- Check patch versioning is in place.
SELECT _v.register_patch('merchant-0008', NULL, NULL);

SET search_path TO merchant;


CREATE TABLE IF NOT EXISTS merchant_issued_tokens
  (issued_token_serial BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
  ,h_contract_terms BYTEA NOT NULL CHECK (LENGTH(h_contract_terms)=64)
  ,token_family_key_serial BIGINT REFERENCES merchant_token_family_keys(token_family_key_serial) ON DELETE CASCADE
  ,blind_sig BYTEA NOT NULL
  );
COMMENT ON TABLE merchant_issued_tokens
 IS 'Tokens that have been (blindly) issued to customers.';
COMMENT ON COLUMN merchant_issued_tokens.h_contract_terms
 IS 'This is no foreign key by design.';
COMMENT ON COLUMN merchant_issued_tokens.token_family_key_serial
 IS 'Token family key to which the spent token belongs.';
COMMENT ON COLUMN merchant_issued_tokens.blind_sig
 IS 'Blind signature made with token issue key to prove validity of token.';

ALTER TABLE merchant_spent_tokens RENAME TO merchant_used_tokens;

ALTER TABLE merchant_token_families ADD COLUMN rounding BIGINT NOT NULL;
COMMENT ON COLUMN merchant_token_families.rounding
 IS 'Token start date rounding granularity.';

ALTER TABLE merchant_token_families RENAME COLUMN redeemed TO used;

-- Complete transaction
COMMIT;
