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

CREATE TABLE IF NOT EXISTS gateway_identity_pairing_start_reservation (
  singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
  attempt_id uuid NOT NULL UNIQUE,
  state text NOT NULL DEFAULT 'starting' CHECK (state IN ('starting','paired')),
  revision_id uuid UNIQUE REFERENCES gateway_identity_configuration_revisions(id) ON DELETE RESTRICT,
  expires_at timestamptz NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT gateway_identity_pairing_start_state_check CHECK (
    (state='starting' AND revision_id IS NULL) OR
    (state='paired' AND revision_id IS NOT NULL)
  )
);

CREATE INDEX IF NOT EXISTS idx_gateway_identity_pairing_start_expiry
  ON gateway_identity_pairing_start_reservation(state,expires_at);

INSERT INTO gateway_identity_pairing_start_reservation(singleton,attempt_id,state,revision_id,expires_at)
SELECT true,exchange.id,'paired',revision.id,exchange.expires_at
FROM gateway_identity_configuration_revisions revision
JOIN gateway_identity_onboarding_exchanges exchange ON exchange.revision_id=revision.id
WHERE revision.state IN ('draft','validated','failed')
  AND NOT (exchange.status='cancelled' AND exchange.cleanup_status='completed')
ORDER BY revision.created_at DESC,exchange.created_at DESC
LIMIT 1
ON CONFLICT DO NOTHING;
