create table if not exists ai_conversation
(
    id                uuid                     default gen_random_uuid()           not null
        primary key,
    user_id           uuid                                                         not null,
    project_id        uuid
        constraint fk_ai_conv_project
            references project
            on delete cascade,
    scope             varchar(16)                                                  not null,
    title             varchar(512),
    model             varchar(128)             default 'gpt-4'::character varying  not null,
    model_config      jsonb,
    status            varchar(32)              default 'active'::character varying not null,
    root_message_id   uuid,
    fork_count        integer                  default 0                           not null,
    is_shared         boolean                  default false                       not null,
    message_count     integer                  default 0                           not null,
    token_usage_total integer,
    created_at        timestamp with time zone default now()                       not null,
    updated_at        timestamp with time zone default now()                       not null,
    access_visibility varchar(32)              default 'owner'::character varying  not null,
    can_ask           varchar(32)              default 'owner'::character varying  not null,
    project_uid       integer,
    model_uid         uuid,
    model_name        varchar(256)
);

create index if not exists idx_ai_conv_user_id
    on ai_conversation (user_id);

create index if not exists idx_ai_conv_project_id
    on ai_conversation (project_id);

create index if not exists idx_ai_conv_scope
    on ai_conversation (scope);

create index if not exists idx_ai_conv_user_created
    on ai_conversation (user_id asc, created_at desc);

create index if not exists idx_ai_conv_project_created
    on ai_conversation (project_id asc, created_at desc);

create index if not exists idx_ai_conv_access_vis
    on ai_conversation (access_visibility);

create index if not exists idx_ai_conv_project_uid
    on ai_conversation (project_id, project_uid)
    where (project_uid IS NOT NULL);
