CREATE TABLE IF NOT EXISTS messages (
    id              BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    uuid            CHAR(36)        NOT NULL,
    conversation_id BIGINT UNSIGNED NOT NULL,
    sender_id       BIGINT UNSIGNED NOT NULL,
    type            ENUM('text','image','video','audio','document','voice_note','video_note','sticker','location','system') NOT NULL DEFAULT 'text',
    content         TEXT            DEFAULT NULL,
    media_id        BIGINT UNSIGNED DEFAULT NULL,
    reply_to_id     BIGINT UNSIGNED DEFAULT NULL,
    forwarded_from  BIGINT UNSIGNED DEFAULT NULL,
    is_edited       TINYINT(1)      DEFAULT 0,
    edited_at       DATETIME        DEFAULT NULL,
    is_deleted      TINYINT(1)      DEFAULT 0,
    deleted_at      DATETIME        DEFAULT NULL,
    duration_ms     INT UNSIGNED    DEFAULT NULL,
    thumbnail_path  VARCHAR(500)    DEFAULT NULL,
    metadata        JSON            DEFAULT NULL,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uq_uuid (uuid),
    FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
    FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE RESTRICT,
    INDEX idx_conv_time (conversation_id, created_at),
    INDEX idx_reply (reply_to_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS message_reads (
    id         BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    message_id BIGINT UNSIGNED NOT NULL,
    user_id    BIGINT UNSIGNED NOT NULL,
    read_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uq_msg_user (message_id, user_id),
    FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_message (message_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
