-- 010-knowledge-bases.sql
-- User/workspace-scoped knowledge base metadata.
--
-- Source indexing details remain in the local workspace source registry because
-- they map local files to provider document/chunk identifiers. The knowledge
-- base entity itself lives in control-plane so ownership, membership and share
-- grants can resolve it consistently across users.

CREATE TABLE IF NOT EXISTS knowledge_bases (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  workspace_id TEXT NOT NULL DEFAULT '',
  root_uri TEXT NOT NULL DEFAULT '',
  name TEXT NOT NULL,
  description TEXT,
  provider TEXT NOT NULL,
  provider_kb_id TEXT NOT NULL,
  default_tool_enabled INTEGER NOT NULL DEFAULT 1,
  can_write INTEGER NOT NULL DEFAULT 1,
  source_count INTEGER NOT NULL DEFAULT 0,
  chunk_count INTEGER NOT NULL DEFAULT 0,
  status TEXT NOT NULL DEFAULT 'active',
  metadata_json TEXT NOT NULL DEFAULT '{}',
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  revision INTEGER NOT NULL DEFAULT 1,
  UNIQUE(user_id, workspace_id, provider, provider_kb_id)
);

CREATE INDEX IF NOT EXISTS idx_knowledge_bases_user_workspace
  ON knowledge_bases(user_id, workspace_id, status, updated_at DESC);

CREATE INDEX IF NOT EXISTS idx_knowledge_bases_root
  ON knowledge_bases(root_uri, status);

CREATE INDEX IF NOT EXISTS idx_knowledge_bases_provider
  ON knowledge_bases(provider, provider_kb_id);
