--
-- This file is part of Challenger
-- Copyright (C) 2026 Taler Systems SA
--
-- Challenger 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.
--
-- Challenger 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
-- Challenger; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--

-- Everything in one big transaction
BEGIN;

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

SET search_path TO challenger;

-- A PIN that was generated for transmission but whose delivery has not
-- been confirmed yet.  It only becomes 'last_pin' once the AUTH_COMMAND
-- helper exited successfully, so that a failed transmission does not
-- invalidate the PIN the user may already hold.
ALTER TABLE validations
  ADD COLUMN pending_pin INT4 DEFAULT NULL;
COMMENT ON COLUMN validations.pending_pin
  IS 'PIN that was passed to the AUTH_COMMAND helper but whose transmission was not confirmed yet; promoted to last_pin when the helper terminates successfully';

-- challenger-0004 made validation_serial_id the primary key, but (unlike for
-- 'clients', where it dropped clients_client_serial_id_key) it left the
-- now redundant UNIQUE constraint from challenger-0001 in place.
ALTER TABLE validations
  DROP CONSTRAINT IF EXISTS validations_validation_serial_id_key;

-- Fix missing 'GENERATED ALWAYS' and UNIQUE constraints on the
-- grant_serial_id
ALTER TABLE tokens
  ADD CONSTRAINT tokens_grant_serial_id_key UNIQUE (grant_serial_id),
  ALTER COLUMN grant_serial_id SET GENERATED ALWAYS;
COMMENT ON COLUMN tokens.grant_serial_id
  IS 'Unique ID of the grant; published by /info as the resource identifier, hence GENERATED ALWAYS: it must not be settable by an INSERT';


COMMIT;
