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

-- Make aml_staff append-only.
--
-- The table used to hold exactly one row per officer, keyed by decider_pub
-- and UPSERTed in place on every status change.  Two things followed from
-- that, both bad.  The officer's history was unrecoverable, so nobody --
-- least of all an auditor -- could answer "was this officer allowed to
-- decide at the time of that decision?".  And because an update left
-- aml_staff_uuid where it was, a status change was invisible to every
-- cursor that walks a table by its serial ID: taler-auditor-sync appends
-- only, so it replicated an officer's first appearance and then silently
-- never carried a single change of it to the auditor's replica.
--
-- From here on the table records one row per status change and the current
-- status of an officer is the row with the greatest last_change.

ALTER TABLE aml_staff
  DROP CONSTRAINT aml_staff_pkey;

-- Redundant once aml_staff_uuid becomes the primary key below.
ALTER TABLE aml_staff
  DROP CONSTRAINT aml_staff_aml_staff_uuid_key;

ALTER TABLE aml_staff
  ADD PRIMARY KEY (aml_staff_uuid);

-- Serves the "most recent status of this officer" lookups (by backward
-- scan), and keeps the exchange from recording the same status twice.
CREATE UNIQUE INDEX aml_staff_by_decider_pub_last_change
  ON aml_staff
  (decider_pub, last_change);

COMMENT ON TABLE aml_staff
  IS 'Status changes of the AML staff members the exchange uses or has used in the past, one row per change. Append-only: the current status of a member is the row with the greatest last_change. Entries never expire as we need to remember the history indefinitely.';
COMMENT ON COLUMN aml_staff.last_change
  IS 'Time from which this status was in force, until superseded by a row with a greater last_change for the same decider_pub. Used to detect replays of old messages.';
