-- 006_pair_tokens.sql — pairing tokens for agent mTLS onboarding.
--
-- An operator generates a token, hands it to a new agent, the agent uses
-- it exactly once to fetch a signed client cert. Tokens expire fast
-- (default 15 min) to limit damage from leaked tokens. token_hash is
-- sha256 of the raw token — we never store the raw value.

CREATE TABLE pair_tokens (
    id            TEXT PRIMARY KEY,              -- pt_<hex16>
    token_hash    TEXT NOT NULL UNIQUE,          -- sha256 hex of the raw token
    description   TEXT NOT NULL DEFAULT '',
    created_by    BIGINT NOT NULL REFERENCES users(id) ON DELETE SET NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at    TIMESTAMPTZ NOT NULL,
    used_at       TIMESTAMPTZ,
    used_by_agent TEXT,                          -- agent_id that consumed it
    issued_cert_fingerprint TEXT
);

CREATE INDEX idx_pair_tokens_hash    ON pair_tokens(token_hash);
CREATE INDEX idx_pair_tokens_expires ON pair_tokens(expires_at);
