using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Domain.Dictionary.ValueObjects;

namespace TakeoutSaaS.Application.Dictionary.Services;

/// <summary>
/// 字典缓存键生成器。
/// </summary>
internal static class DictionaryCacheKeys
{
    internal const string DictionaryPrefix = "dict:";
    internal const string GroupPrefix = "dict:groups:";
    internal const string ItemPrefix = "dict:items:";

    internal static string BuildDictionaryKey(long tenantId, DictionaryCode code)
        => $"{DictionaryPrefix}{tenantId}:{code.Value}";

    internal static string BuildGroupKey(
        long tenantId,
        DictionaryScope scope,
        int page,
        int pageSize,
        string? keyword,
        bool? isEnabled,
        string? sortBy,
        bool sortDescending)
    {
        return $"{GroupPrefix}{tenantId}:{scope}:{page}:{pageSize}:{Normalize(keyword)}:{Normalize(isEnabled)}:{Normalize(sortBy)}:{(sortDescending ? "desc" : "asc")}";
    }

    internal static string BuildGroupPrefix(long tenantId)
        => $"{GroupPrefix}{tenantId}:";

    internal static string BuildItemKey(long groupId)
        => $"{ItemPrefix}{groupId}";

    private static string Normalize(string? value)
        => string.IsNullOrWhiteSpace(value)
            ? "all"
            : value.Trim().ToLowerInvariant().Replace(":", "_", StringComparison.Ordinal);

    private static string Normalize(bool? value)
        => value.HasValue ? (value.Value ? "1" : "0") : "all";
}
