CREATE TABLE IF NOT EXISTS agent_setup_codes (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  agent_id uuid NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
  code_hash text NOT NULL UNIQUE,
  code_suffix text,
  status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'used', 'expired', 'revoked')),
  token_name text NOT NULL DEFAULT 'Local Codex token',
  created_by_user_id text,
  expires_at timestamptz NOT NULL,
  used_at timestamptz,
  used_token_id uuid REFERENCES agent_tokens(id) ON DELETE SET NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS agent_setup_codes_agent_id_idx ON agent_setup_codes(agent_id);
CREATE INDEX IF NOT EXISTS agent_setup_codes_status_idx ON agent_setup_codes(status);
CREATE INDEX IF NOT EXISTS agent_setup_codes_expires_at_idx ON agent_setup_codes(expires_at);
