-- Conversation and Usage Tracking
-- Migration: 004_conversations.sql

-- Store conversation message history
CREATE TABLE conversation_messages (
    conversation_id TEXT PRIMARY KEY,
    user_id TEXT,
    messages JSONB NOT NULL DEFAULT '[]'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_conversations_user ON conversation_messages(user_id, updated_at DESC);

-- Track LLM usage for cost monitoring
CREATE TABLE usage_records (
    id SERIAL PRIMARY KEY,
    user_id TEXT NOT NULL,
    agent_name TEXT NOT NULL,
    model TEXT NOT NULL,
    request_tokens INTEGER NOT NULL DEFAULT 0,
    response_tokens INTEGER NOT NULL DEFAULT 0,
    total_tokens INTEGER NOT NULL DEFAULT 0,
    requests INTEGER NOT NULL DEFAULT 1,
    cost_estimate DECIMAL(10, 6) NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_usage_user ON usage_records(user_id, created_at DESC);
CREATE INDEX idx_usage_agent ON usage_records(agent_name);
