-- P2: AI tool events (receipts) and file patches for per-user/per-session query.
-- See design/07-ai/process/7-71-unified-ai-management-control-plane-and-pi-lab-integration-v1.md

CREATE TABLE IF NOT EXISTS ai_tool_events (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    workspace_id TEXT,
    session_id TEXT NOT NULL,
    run_id TEXT,
    provider TEXT NOT NULL,
    provider_session_id TEXT,
    tool_name TEXT NOT NULL,
    allowed INTEGER NOT NULL DEFAULT 1,
    deny_reason TEXT,
    root_uri TEXT NOT NULL,
    page_path TEXT,
    normalized_file_path TEXT,
    diff_summary TEXT,
    citation_count INTEGER NOT NULL DEFAULT 0,
    before_file_version TEXT,
    after_file_version TEXT,
    payload_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    deleted_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_ai_tool_events_user_session
ON ai_tool_events(user_id, session_id, created_at);

CREATE INDEX IF NOT EXISTS idx_ai_tool_events_user_run
ON ai_tool_events(user_id, run_id, created_at);

CREATE TABLE IF NOT EXISTS ai_file_patches (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    workspace_id TEXT,
    session_id TEXT NOT NULL,
    run_id TEXT,
    tool_event_id TEXT NOT NULL REFERENCES ai_tool_events(id) ON DELETE CASCADE,
    root_uri TEXT NOT NULL DEFAULT '',
    relative_path TEXT NOT NULL,
    before_file_version TEXT,
    after_file_version TEXT,
    patch_summary_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    deleted_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_ai_file_patches_user_session
ON ai_file_patches(user_id, session_id, created_at);

CREATE INDEX IF NOT EXISTS idx_ai_file_patches_user_run
ON ai_file_patches(user_id, run_id, created_at);

CREATE INDEX IF NOT EXISTS idx_ai_file_patches_tool_event
ON ai_file_patches(tool_event_id);
