-- IT0 Migration 004: Add conversation_messages table for multi-turn context management
-- This table stores conversation history per session, shared across all engine types.
-- Usage: Replace {SCHEMA} with target schema name (e.g., it0_t_t001)

SET search_path TO {SCHEMA};

-- Conversation Messages (multi-turn dialogue history per session)
CREATE TABLE IF NOT EXISTS conversation_messages (
    id                UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id         VARCHAR(20) NOT NULL,
    session_id        UUID NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
    role              VARCHAR(20) NOT NULL,
    content           TEXT NOT NULL,
    tool_calls        JSONB,
    tool_results      JSONB,
    attachments       JSONB,
    token_count       INTEGER,
    sequence_number   INTEGER NOT NULL,
    created_at        TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Migration: Add attachments column to existing tables
ALTER TABLE conversation_messages ADD COLUMN IF NOT EXISTS attachments JSONB;

CREATE INDEX IF NOT EXISTS idx_conversation_messages_session
    ON conversation_messages(session_id, sequence_number ASC);
CREATE INDEX IF NOT EXISTS idx_conversation_messages_session_recent
    ON conversation_messages(session_id, sequence_number DESC);
