CREATE TABLE IF NOT EXISTS ai_message (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    conversation_id UUID NOT NULL,
    parent_message_id UUID,
    role VARCHAR(16) NOT NULL,
    content JSONB NOT NULL,
    model VARCHAR(128),
    is_fork_origin BOOLEAN NOT NULL DEFAULT false,
    stop_reason VARCHAR(32),
    input_tokens INT,
    output_tokens INT,
    latency_ms INT,
    metadata JSONB,
    room_id UUID,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_ai_msg_conv ON ai_message (conversation_id, created_at);
CREATE INDEX IF NOT EXISTS idx_ai_msg_parent ON ai_message (parent_message_id);

ALTER TABLE ai_message
    ADD CONSTRAINT fk_ai_msg_conv
    FOREIGN KEY (conversation_id) REFERENCES ai_conversation(id) ON DELETE CASCADE;

ALTER TABLE ai_message
    ADD CONSTRAINT fk_ai_msg_parent
    FOREIGN KEY (parent_message_id) REFERENCES ai_message(id) ON DELETE SET NULL;
