--
-- 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/>
--
-- @author Özgür Kesim

CREATE FUNCTION create_table_withdraw(
  IN partition_suffix TEXT DEFAULT NULL
)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'withdraw';
BEGIN
  PERFORM create_partitioned_table(
    'CREATE TABLE %I'
      '(withdraw_id BIGINT GENERATED BY DEFAULT AS IDENTITY'
      ',planchets_h BYTEA CONSTRAINT planchets_h_length CHECK(LENGTH(planchets_h)=64)'
      ',execution_date INT8 NOT NULL'
      ',amount_with_fee taler_amount NOT NULL'
      ',reserve_pub BYTEA NOT NULL CONSTRAINT reserve_pub_length CHECK(LENGTH(reserve_pub)=32)'
      ',reserve_sig BYTEA NOT NULL CONSTRAINT reserve_sig_length CHECK(LENGTH(reserve_sig)=64)'
      ',max_age SMALLINT CONSTRAINT max_age_positive CHECK(max_age>=0)'
      ',noreveal_index SMALLINT CONSTRAINT noreveal_index_positive CHECK(noreveal_index>=0)'
      ',selected_h BYTEA CONSTRAINT selected_h_length CHECK(LENGTH(selected_h)=64)'
      ',blinding_seed BYTEA CONSTRAINT blinding_seed_length CHECK(LENGTH(blinding_seed)>=32)'
      ',cs_r_values BYTEA[]'
      ',cs_r_choices INT8'
      ',denom_serials INT8[] NOT NULL CONSTRAINT denom_serials_array_length CHECK(cardinality(denom_serials)=cardinality(denom_sigs))'
      ',denom_sigs BYTEA[] NOT NULL CONSTRAINT denom_sigs_array_length CHECK(cardinality(denom_sigs)=cardinality(denom_serials))'
    ') %s ;'
    ,table_name
    ,'PARTITION BY HASH (reserve_pub)'
    ,partition_suffix
  );
  PERFORM comment_partitioned_table(
     'Commitments made when withdrawing coins and, in case of required proof of age restriction, the gamma value chosen by the exchange. '
     'It also contains the blindly signed coins, their signatures and denominations.'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'If the client explicitly commits to age-restricted coins, the gamma value chosen by the exchange in the cut-and-choose protocol; might be NULL.'
    ,'noreveal_index'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The running hash over all committed blinded planchets. Needed for recoup and (when a proof of age-restriction was required)'
     ' in the subsequent cut-and-choose protocol.'
    ,'planchets_h'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The date of execution of this withdrawal, according to the exchange'
    ,'execution_date'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'If the clients commits to age-restricted coins, the maximum age (in years) that the client explicitly commits to with this request; might be NULL.'
    ,'max_age'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Reference to the public key of the reserve from which the coins are going to be withdrawn'
    ,'reserve_pub'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Signature of the reserve''s private key over the withdraw request'
    ,'reserve_sig'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Array of references to the denominations'
    ,'denom_serials'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'In case of age restriction, the hash of the chosen (noreveal_index) blinded envelopes.'
    ,'selected_h'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Array of signatures over each blinded envelope.  If age-proof was not required, the signed envelopes are the ones'
     ' hashed into planchet_h.  Otherwise (when age-proof is required) the selected planchets (noreveal_index) were signed,'
     ' hashed into selected_h.'
    ,'denom_sigs'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The master seed for the blinding nonces, needed for blind CS signatures; maybe NULL'
    ,'blinding_seed'
    ,table_name
    ,partition_suffix
  );
 PERFORM comment_partitioned_column(
     'The pairs of R-values (calculated by the exchange) for the coins of cipher type Clause-Schnorr, based on the blinding_seed; maybe NULL.'
    ,'cs_r_values'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The bitvector of choices made by the exchange for each of the pairs in cs_r_values; maybe NULL.'
     'The vector is stored in network byte order and the lowest bit corresponds to the 0-th entry in cs_r_values (pair)'
    ,'cs_r_choices'
    ,table_name
    ,partition_suffix
  );
END
$$;


CREATE FUNCTION constrain_table_withdraw(
  IN partition_suffix TEXT
)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'withdraw';
BEGIN
  table_name = concat_ws('_', table_name, partition_suffix);
  EXECUTE FORMAT (
    'CREATE INDEX ' || table_name || '_by_reserve_pub_index '
    'ON ' || table_name || ' '
    '(reserve_pub);'
  );
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD PRIMARY KEY (reserve_pub, planchets_h);'
  );
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD CONSTRAINT ' || table_name || '_withdraw_id_key'
    ' UNIQUE (withdraw_id);'
  );
END
$$;


CREATE FUNCTION foreign_table_withdraw()
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'withdraw';
BEGIN
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD CONSTRAINT ' || table_name || '_foreign_reserve_pub'
    ' FOREIGN KEY (reserve_pub)'
    ' REFERENCES reserves(reserve_pub) ON DELETE CASCADE;'
  );
END
$$;

-- Trigger to update the reserve_history table
CREATE FUNCTION withdraw_insert_trigger()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
  INSERT INTO reserve_history
    (reserve_pub
    ,table_name
    ,serial_id)
  VALUES
    (NEW.reserve_pub
    ,'withdraw'
    ,NEW.withdraw_id);
  RETURN NEW;
END $$;
COMMENT ON FUNCTION withdraw_insert_trigger()
  IS 'Keep track of a particular withdraw in the reserve_history table.';

-- Trigger to update the unique_withdraw_blinding_seed table
CREATE FUNCTION withdraw_delete_trigger()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
  DELETE FROM unique_withdraw_blinding_seed
  WHERE blinding_seed = OLD.blinding_seed;
  RETURN OLD;
END $$;
COMMENT ON FUNCTION withdraw_delete_trigger()
  IS 'Delete blinding_seed from unique_withdraw_blinding_seed table.';

-- Put the triggers into the master table
CREATE FUNCTION master_table_withdraw()
  RETURNS void
  LANGUAGE plpgsql
  AS $$
BEGIN
  CREATE TRIGGER withdraw_on_insert
  AFTER INSERT
  ON withdraw
  FOR EACH ROW EXECUTE FUNCTION withdraw_insert_trigger();

  CREATE TRIGGER withdraw_on_delete
  AFTER DELETE
  ON withdraw
  FOR EACH ROW EXECUTE FUNCTION withdraw_delete_trigger();
END $$;
COMMENT ON FUNCTION master_table_withdraw()
  IS 'Setup triggers to replicate withdraw into reserve_history and delete blinding_seed from unique_withdraw_blinding_seed.';


INSERT INTO exchange_tables
  (name
  ,version
  ,action
  ,partitioned
  ,by_range)
VALUES
  ('withdraw', 'exchange-0002', 'create',   TRUE ,FALSE),
  ('withdraw', 'exchange-0002', 'constrain',TRUE ,FALSE),
  ('withdraw', 'exchange-0002', 'foreign',  TRUE ,FALSE),
  ('withdraw', 'exchange-0002', 'master',   TRUE ,FALSE);

