using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Core.Blueprint.Redis.Helpers
{
    /// 
    /// Helper class for generating consistent and normalized cache keys.
    /// 
    public static class CacheKeyHelper
    {
        /// 
        /// Generates a cache key based on the instance, method name, and parameters.
        /// 
        /// The instance of the class.
        /// The method name related to the cache key.
        /// The parameters used to generate the key.
        /// A normalized cache key string.
        public static string GenerateCacheKey(object instance, string methodName, params object[] parameters)
        {
            var className = instance.GetType().Name;
            var keyBuilder = new StringBuilder($"{className}.{methodName}");
            foreach (var param in parameters)
            {
                string normalizedParam = NormalizeParameter(param);
                keyBuilder.Append($".{normalizedParam}");
            }
            return keyBuilder.ToString();
        }
        /// 
        /// Normalizes a parameter value for use in a cache key.
        /// 
        /// The parameter to normalize.
        /// A normalized string representation of the parameter.
        private static string NormalizeParameter(object param)
        {
            if (param == null)
            {
                return "null";
            }
            string paramString;
            if (param is DateTime dateTime)
            {
                paramString = dateTime.ToString("yyyyMMdd");
            }
            else
            {
                paramString = param.ToString();
            }
            // Replace special characters with an underscore.
            return Regex.Replace(paramString, @"[^a-zA-Z0-9]", "_");
        }
    }
}