SET @assigned_col_exists := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'chat_channels'
      AND column_name = 'assigned_user_id'
);
SET @assigned_col_sql := IF(
    @assigned_col_exists = 0,
    'ALTER TABLE chat_channels ADD COLUMN assigned_user_id BIGINT UNSIGNED NULL AFTER contact_id',
    'SELECT 1'
);
PREPARE stmt FROM @assigned_col_sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @assigned_idx_exists := (
    SELECT COUNT(*)
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'chat_channels'
      AND index_name = 'idx_chat_channels_assigned_user'
);
SET @assigned_idx_sql := IF(
    @assigned_idx_exists = 0,
    'ALTER TABLE chat_channels ADD KEY idx_chat_channels_assigned_user (assigned_user_id)',
    'SELECT 1'
);
PREPARE stmt FROM @assigned_idx_sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
