--
-- 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_refresh(
  IN partition_suffix TEXT DEFAULT NULL
)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'refresh';
BEGIN
  PERFORM create_partitioned_table(
    'CREATE TABLE %I'
      '(refresh_id BIGINT GENERATED BY DEFAULT AS IDENTITY'
      ',rc BYTEA PRIMARY KEY CONSTRAINT rc_length CHECK(LENGTH(rc)=64)'
      ',execution_date INT8 NOT NULL'
      ',amount_with_fee taler_amount NOT NULL'
      ',old_coin_pub BYTEA NOT NULL'
      ',old_coin_sig BYTEA NOT NULL CHECK(LENGTH(old_coin_sig)=64)'
      ',refresh_seed BYTEA NOT NULL'
      ',noreveal_index INT4 NOT NULL  CONSTRAINT noreveal_index_positive CHECK(noreveal_index>=0)'
      ',planchets_h BYTEA CONSTRAINT planchets_h_length CHECK(LENGTH(planchets_h)=64)'
      ',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 (rc)'
    ,partition_suffix
  );
  PERFORM comment_partitioned_table(
    'The data provided by the client for the melting operation of an old coin and he choices made by the exchange '
    ' with respect to the cut-and-choose protocol: nonreveal_index and the corresponding chosen'
    ' blinded coin envelope along with the denomination signatures at the moment of the melting.'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The hash over the refresh request, which serves as the primary key'
     ' for the lookup during the reveal phase.'
    ,'rc'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The publice nonce from which all other nonces for all n*kappa coin candidates are derived for which'
     ' the old coin proves ownership via signatures'
    ,'refresh_seed'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The gamma value chosen by the exchange in the cut-and-choose protocol'
    ,'noreveal_index'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The date of execution of the melting operation, according to the exchange'
    ,'execution_date'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Reference to the public key of the old coin which is melted'
    ,'old_coin_pub'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Signature of the old coin''s private key over the melt request'
    ,'old_coin_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(
     '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 public pairs of R-values provided by the exchange for the CS denominations; might be 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
  );
  PERFORM comment_partitioned_column(
     'The hash over all kappa*n blinded planchets that were provided by the client'
    ,'planchets_h'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'The hash over the n blinded planchets that were selected by the exchange.'
    ,'selected_h'
    ,table_name
    ,partition_suffix
  );
  PERFORM comment_partitioned_column(
     'Array of signatures, one for each blinded envelope'
    ,'denom_sigs'
    ,table_name
    ,partition_suffix
  );
END
$$;


CREATE FUNCTION constrain_table_refresh(
  IN partition_suffix TEXT
)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'refresh';
BEGIN
  table_name = concat_ws('_', table_name, partition_suffix);
  -- Note: index spans partitions, may need to be materialized.
  EXECUTE FORMAT (
    'CREATE INDEX ' || table_name || '_by_old_coin_pub_index '
    'ON ' || table_name || ' '
    '(old_coin_pub);'
  );
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD CONSTRAINT ' || table_name || '_refresh_id_key'
    ' UNIQUE (refresh_id);'
  );
END
$$;


CREATE FUNCTION foreign_table_refresh()
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
  table_name TEXT DEFAULT 'refresh';
BEGIN
  EXECUTE FORMAT (
    'ALTER TABLE ' || table_name ||
    ' ADD CONSTRAINT ' || table_name || '_foreign_coin_pub'
    ' FOREIGN KEY (old_coin_pub) '
    ' REFERENCES known_coins (coin_pub) ON DELETE CASCADE'
  );
END
$$;


-- Trigger to update the reserve_history table
CREATE FUNCTION refresh_insert_trigger()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
  INSERT INTO coin_history
    (coin_pub
    ,table_name
    ,serial_id)
  VALUES
    (NEW.old_coin_pub
    ,'refresh'
    ,NEW.refresh_id);
  RETURN NEW;
END $$;
COMMENT ON FUNCTION refresh_insert_trigger()
  IS 'Keep track of a particular refresh in the coin_history table.';

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

-- Put the triggers into the master table
CREATE FUNCTION master_table_refresh()
  RETURNS void
  LANGUAGE plpgsql
  AS $$
BEGIN
  CREATE TRIGGER refresh_on_insert
  AFTER INSERT
  ON refresh
  FOR EACH ROW EXECUTE FUNCTION refresh_insert_trigger();

  CREATE TRIGGER refresh_on_delete
  AFTER DELETE
  ON refresh
  FOR EACH ROW EXECUTE FUNCTION refresh_delete_trigger();
END $$;
COMMENT ON FUNCTION master_table_refresh()
  IS 'Setup triggers to replicate refresh into coin_history and delete blinding_seed from unique_refresh_blinding_seed.';


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

