CREATE TABLE  family_threads
(
    id                BIGSERIAL PRIMARY KEY,
    family_id         BIGINT    NOT NULL REFERENCES families (id) ON DELETE CASCADE,
    type              TEXT      NOT NULL,
    title             TEXT      NOT NULL,
    telegram_topic_id BIGINT    NOT NULL,
    is_system         BOOLEAN   NOT NULL DEFAULT FALSE,
    created_by        BIGINT    NOT NULL REFERENCES users (id),
    created_at        TIMESTAMP NOT NULL DEFAULT NOW(),

    UNIQUE (family_id, telegram_topic_id)
);

CREATE UNIQUE INDEX idx_unique_system_threads ON family_threads (family_id, type) WHERE is_system = TRUE;

CREATE INDEX idx_threads_family_id ON family_threads (family_id);

CREATE INDEX idx_threads_family_type ON family_threads (family_id, type);
