create table if not exists ai_message
(
    id                uuid                     default gen_random_uuid() not null
        primary key,
    conversation_id   uuid                                               not null
        constraint fk_ai_msg_conv
            references ai_conversation
            on delete cascade,
    parent_message_id uuid
        constraint fk_ai_msg_parent
            references ai_message
            on delete set null,
    role              varchar(16)                                        not null,
    content           jsonb                                              not null,
    model             varchar(128),
    is_fork_origin    boolean                  default false             not null,
    stop_reason       varchar(32),
    input_tokens      integer,
    output_tokens     integer,
    latency_ms        integer,
    metadata          jsonb,
    room_id           uuid,
    created_at        timestamp with time zone default now()             not null
);

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);
