-- LLM Configurations Table
CREATE TABLE IF NOT EXISTS llm_configs (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    provider VARCHAR(50) NOT NULL,
    api_key_encrypted TEXT NOT NULL,
    model VARCHAR(100),
    temperature DECIMAL(3, 2) DEFAULT 0.7,
    max_tokens INTEGER DEFAULT 2048,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(user_id, provider)
);

CREATE INDEX idx_llm_configs_user ON llm_configs(user_id);

-- LLM Chat History Table
CREATE TABLE IF NOT EXISTS llm_chat_history (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    provider VARCHAR(50) NOT NULL,
    role VARCHAR(20) NOT NULL,
    content TEXT NOT NULL,
    tokens_used INTEGER,
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_llm_history_user_provider ON llm_chat_history(user_id, provider, created_at DESC);

-- Add comments
COMMENT ON TABLE llm_configs IS 'Stores encrypted API keys and configurations for LLM providers';
COMMENT ON TABLE llm_chat_history IS 'Stores chat message history for each provider';
COMMENT ON COLUMN llm_configs.api_key_encrypted IS 'AES-256-GCM encrypted API key';
COMMENT ON COLUMN llm_configs.temperature IS 'LLM temperature parameter (0.0 - 2.0)';
COMMENT ON COLUMN llm_configs.max_tokens IS 'Maximum tokens for LLM responses';
