-- ai_proactive plugin: suggestions, context log, user settings

-- Suggestions Store
CREATE TABLE IF NOT EXISTS ai_proactive_suggestions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    user_id UUID NOT NULL,
    entity_type VARCHAR(50) NOT NULL,
    entity_id UUID,
    suggestion_type VARCHAR(50) NOT NULL DEFAULT 'info',  -- info, warning, action, insight
    title VARCHAR(200) NOT NULL,
    content TEXT NOT NULL,
    confidence FLOAT NOT NULL DEFAULT 0.5,
    actions JSONB NOT NULL DEFAULT '[]',  -- [{method, path, body, description}]
    is_dismissed BOOLEAN NOT NULL DEFAULT FALSE,
    is_acted_upon BOOLEAN NOT NULL DEFAULT FALSE,
    context_snapshot JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at TIMESTAMPTZ,
    deleted_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS ix_suggestions_user ON ai_proactive_suggestions (tenant_id, user_id, is_dismissed, created_at DESC);
CREATE INDEX IF NOT EXISTS ix_suggestions_entity ON ai_proactive_suggestions (tenant_id, entity_type, entity_id);

-- Context Log (was der User wann angesehen hat)
CREATE TABLE IF NOT EXISTS ai_proactive_context_log (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    user_id UUID NOT NULL,
    page VARCHAR(200) NOT NULL,
    entity_type VARCHAR(50),
    entity_id UUID,
    entity_data JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS ix_context_log_user_time ON ai_proactive_context_log (tenant_id, user_id, created_at DESC);

-- User Settings für proactive AI
CREATE TABLE IF NOT EXISTS ai_proactive_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    user_id UUID NOT NULL,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    suggestion_categories JSONB NOT NULL DEFAULT '["mail","tasks","contacts","companies","insights"]',
    confidence_threshold FLOAT NOT NULL DEFAULT 0.5,
    rate_limit_seconds INT NOT NULL DEFAULT 10,
    model VARCHAR(100) NOT NULL DEFAULT 'gpt-4o-mini',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    UNIQUE(tenant_id, user_id)
);
