--
-- 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-0004', NULL, NULL);

SET search_path TO challenger;

-- need to drop this before converting UNIQUE to PK
ALTER TABLE validations
  DROP CONSTRAINT validations_client_serial_id_fkey;

-- convert UNIQUE index to PK
ALTER TABLE clients
  ADD CONSTRAINT clients_serial_pkey PRIMARY KEY (client_serial_id),
  DROP CONSTRAINT clients_client_serial_id_key;

-- Set non-NULLable where the C code reads
-- fields through non-nullable result specs,
-- add missing pK, and re-add foreign key constraint
ALTER TABLE validations
  ALTER COLUMN nonce SET NOT NULL,
  ALTER COLUMN address_attempts_left SET NOT NULL,
  ALTER COLUMN pin_transmissions_left SET NOT NULL,
  ALTER COLUMN auth_attempts_left SET NOT NULL,
  ADD CONSTRAINT validation_serial_pkey PRIMARY KEY (validation_serial_id),
  ADD CONSTRAINT validations_client_serial_id_fkey
    FOREIGN KEY (client_serial_id)
    REFERENCES clients(client_serial_id)
    ON DELETE CASCADE;

-- Add missing index for FK cascade drop
CREATE INDEX validations_by_client
  ON validations(client_serial_id);
COMMENT ON INDEX validations_by_client
  IS 'Index needed for foreign key constraint validations_client_serial_id_fkey';


COMMIT;
