namespace FireflyClient
{
    public partial class FireflyClient
    {
        #region Hash Operations
        
        /// <summary>
        /// Sets a field in a hash
        /// </summary>
        public bool HashSet(string key, string field, string value)
        {
            string response = ExecuteCommand("HSET", key, field, value);
            return response.StartsWith(":1");
        }
        
        /// <summary>
        /// Gets a field from a hash
        /// </summary>
        public string HashGet(string key, string field)
        {
            string response = ExecuteCommand("HGET", key, field);
            if (response.StartsWith('+'))
            {
                return response[1..].TrimEnd('\r', '\n');
            }
            return string.Empty;
        }
        
        /// <summary>
        /// Deletes a field from a hash
        /// </summary>
        public bool HashDelete(string key, string field)
        {
            string response = ExecuteCommand("HDEL", key, field);
            return response.StartsWith(":1");
        }
        
        /// <summary>
        /// Checks if a field exists in a hash
        /// </summary>
        public bool HashFieldExists(string key, string field)
        {
            string response = ExecuteCommand("HEXISTS", key, field);
            return response.StartsWith(":1");
        }
        
        /// <summary>
        /// Gets all fields and values from a hash
        /// </summary>
        public Dictionary<string, string> HashGetAll(string key)
        {
            string response = ExecuteCommand("HGETALL", key);
            List<string> items = ParseArrayResponse(response);
            
            var result = new Dictionary<string, string>();
            for (int i = 0; i < items.Count; i += 2)
            {
                if (i + 1 < items.Count)
                {
                    result[items[i]] = items[i + 1];
                }
            }
            
            return result;
        }
        
        /// <summary>
        /// Sets multiple fields in a hash at once
        /// </summary>
        public bool HashMultiSet(string key, Dictionary<string, string> fieldValues)
        {
            List<string> args = [key];
            
            foreach (var kvp in fieldValues)
            {
                args.Add(kvp.Key);
                args.Add(kvp.Value);
            }
            
            string response = ExecuteCommand("HMSET", [.. args]);
            return response.StartsWith("+OK");
        }
        
        #endregion
    }
}