-- Migration: V010_create_ai_conversations
-- Description: Create AI conversation history table
-- Author: System
-- Date: 2025-10-01

-- Create ai_conversations table
CREATE TABLE IF NOT EXISTS ai_conversations (
    id VARCHAR(20) PRIMARY KEY,
    user_id VARCHAR(20) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    messages JSONB DEFAULT '[]'::jsonb,
    total_tokens INTEGER DEFAULT 0,
    context_summary TEXT,
    metadata JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for performance
CREATE INDEX idx_ai_conversations_user ON ai_conversations(user_id);
CREATE INDEX idx_ai_conversations_created ON ai_conversations(created_at DESC);
CREATE INDEX idx_ai_conversations_user_created ON ai_conversations(user_id, created_at DESC);

-- Add comments
COMMENT ON TABLE ai_conversations IS 'Stores AI chat conversation history';
COMMENT ON COLUMN ai_conversations.messages IS 'Array of conversation messages with role, content, and timestamp';
COMMENT ON COLUMN ai_conversations.total_tokens IS 'Total tokens used in this conversation';
COMMENT ON COLUMN ai_conversations.context_summary IS 'Summary of conversation context for future reference';
COMMENT ON COLUMN ai_conversations.metadata IS 'Additional conversation metadata (child context, etc.)';
