SET LOCAL lock_timeout = '10s';
SET LOCAL statement_timeout = '60s';

ALTER TABLE gateway_identity_secret_cleanup_queue
  ADD COLUMN IF NOT EXISTS status text,
  ADD COLUMN IF NOT EXISTS claim_token uuid,
  ADD COLUMN IF NOT EXISTS lease_expires_at timestamptz;

ALTER TABLE gateway_identity_secret_cleanup_queue
  DROP CONSTRAINT IF EXISTS gateway_identity_secret_cleanup_status_check,
  DROP CONSTRAINT IF EXISTS gateway_identity_secret_cleanup_claim_check;

UPDATE gateway_identity_secret_cleanup_queue
SET status='pending',claim_token=NULL,lease_expires_at=NULL,updated_at=now()
WHERE status IS NULL
   OR status NOT IN ('pending','claimed')
   OR (status='pending' AND (claim_token IS NOT NULL OR lease_expires_at IS NOT NULL))
   OR (status='claimed' AND (claim_token IS NULL OR lease_expires_at IS NULL));

ALTER TABLE gateway_identity_secret_cleanup_queue
  ALTER COLUMN status SET DEFAULT 'pending',
  ALTER COLUMN status SET NOT NULL,
  ADD CONSTRAINT gateway_identity_secret_cleanup_status_check
    CHECK (status IN ('pending','claimed')),
  ADD CONSTRAINT gateway_identity_secret_cleanup_claim_check
    CHECK (
      (status='pending' AND claim_token IS NULL AND lease_expires_at IS NULL) OR
      (status='claimed' AND claim_token IS NOT NULL AND lease_expires_at IS NOT NULL)
    );

DROP INDEX IF EXISTS idx_gateway_identity_secret_cleanup_due;

CREATE INDEX idx_gateway_identity_secret_cleanup_due
  ON gateway_identity_secret_cleanup_queue(status,not_before,lease_expires_at,updated_at);
