namespace DramaLing.Api.Services.Caching;

/// <summary>
/// 智能快取服務介面，支援多層快取策略
/// </summary>
public interface ICacheService
{
    /// <summary>
    /// 取得快取值
    /// </summary>
    /// <typeparam name="T">快取值類型</typeparam>
    /// <param name="key">快取鍵</param>
    /// <returns>快取值</returns>
    Task<T?> GetAsync<T>(string key) where T : class;

    /// <summary>
    /// 設定快取值
    /// </summary>
    /// <typeparam name="T">快取值類型</typeparam>
    /// <param name="key">快取鍵</param>
    /// <param name="value">快取值</param>
    /// <param name="expiry">過期時間</param>
    /// <returns>是否成功</returns>
    Task<bool> SetAsync<T>(string key, T value, TimeSpan? expiry = null) where T : class;

    /// <summary>
    /// 移除快取值
    /// </summary>
    /// <param name="key">快取鍵</param>
    /// <returns>是否成功</returns>
    Task<bool> RemoveAsync(string key);

    /// <summary>
    /// 檢查快取是否存在
    /// </summary>
    /// <param name="key">快取鍵</param>
    /// <returns>是否存在</returns>
    Task<bool> ExistsAsync(string key);

    /// <summary>
    /// 設定快取過期時間
    /// </summary>
    /// <param name="key">快取鍵</param>
    /// <param name="expiry">過期時間</param>
    /// <returns>是否成功</returns>
    Task<bool> ExpireAsync(string key, TimeSpan expiry);

    /// <summary>
    /// 清除所有快取
    /// </summary>
    /// <returns>是否成功</returns>
    Task<bool> ClearAsync();

    /// <summary>
    /// 批次操作
    /// </summary>
    /// <typeparam name="T">快取值類型</typeparam>
    /// <param name="keys">快取鍵列表</param>
    /// <returns>快取值字典</returns>
    Task<Dictionary<string, T?>> GetManyAsync<T>(IEnumerable<string> keys) where T : class;

    /// <summary>
    /// 批次設定
    /// </summary>
    /// <typeparam name="T">快取值類型</typeparam>
    /// <param name="keyValuePairs">鍵值對</param>
    /// <param name="expiry">過期時間</param>
    /// <returns>是否成功</returns>
    Task<bool> SetManyAsync<T>(Dictionary<string, T> keyValuePairs, TimeSpan? expiry = null) where T : class;

    /// <summary>
    /// 取得快取統計資訊
    /// </summary>
    /// <returns>快取統計</returns>
    Task<CacheStats> GetStatsAsync();
}

/// <summary>
/// 快取統計資訊
/// </summary>
public class CacheStats
{
    public int TotalKeys { get; set; }
    public long TotalMemoryUsage { get; set; }
    public int HitCount { get; set; }
    public int MissCount { get; set; }
    public double HitRate => TotalRequests > 0 ? (double)HitCount / TotalRequests : 0;
    public int TotalRequests => HitCount + MissCount;
    public DateTime LastUpdated { get; set; }
}