CREATE TABLE IF NOT EXISTS ai_external_conversation_bindings (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    workspace_id TEXT,
    mnote_session_id TEXT NOT NULL,
    acp_session_id TEXT,
    agent_id TEXT NOT NULL,
    profile TEXT NOT NULL,
    provider TEXT NOT NULL,
    remote_conversation_id TEXT NOT NULL,
    remote_url TEXT,
    status TEXT NOT NULL DEFAULT 'active',
    metadata_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    deleted_at TEXT,
    revision INTEGER NOT NULL DEFAULT 1,
    CHECK (status IN ('active', 'local_deleted', 'remote_deleted', 'remote_delete_failed', 'remote_missing'))
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_external_conv_user_session_provider
ON ai_external_conversation_bindings(user_id, mnote_session_id, provider);

CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_external_conv_user_provider_remote
ON ai_external_conversation_bindings(user_id, provider, remote_conversation_id);

CREATE INDEX IF NOT EXISTS idx_ai_external_conv_lookup
ON ai_external_conversation_bindings(user_id, workspace_id, mnote_session_id, provider, status);
