using System.Text.Json;
using TakeoutSaaS.Application.App.Stores.Dto;

namespace TakeoutSaaS.Application.App.Stores;

/// <summary>
/// 打包费阶梯 JSON 辅助方法。
/// </summary>
public static class StoreFeeTierHelper
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);

    public static IReadOnlyList<StoreFeeTierDto> Deserialize(string? json)
    {
        if (string.IsNullOrWhiteSpace(json))
        {
            return [];
        }

        try
        {
            return JsonSerializer.Deserialize<List<StoreFeeTierDto>>(json, JsonOptions) ?? [];
        }
        catch (JsonException)
        {
            return [];
        }
    }

    public static string? Serialize(IReadOnlyList<StoreFeeTierDto> tiers)
    {
        if (tiers.Count == 0)
        {
            return null;
        }

        return JsonSerializer.Serialize(tiers, JsonOptions);
    }

    public static IReadOnlyList<StoreFeeTierDto> Normalize(IReadOnlyList<StoreFeeTierDto> tiers)
    {
        if (tiers.Count == 0)
        {
            return [];
        }

        var normalized = new List<StoreFeeTierDto>(tiers.Count);
        var currentMin = 0m;
        foreach (var tier in tiers)
        {
            normalized.Add(new StoreFeeTierDto
            {
                MinPrice = currentMin,
                MaxPrice = tier.MaxPrice,
                Fee = tier.Fee
            });
            if (tier.MaxPrice.HasValue)
            {
                currentMin = tier.MaxPrice.Value;
            }
        }

        return normalized;
    }
}
