using System.Text.Json;

namespace Tiku.Infrastructure.Jobs;

internal static class BackgroundJobPayload
{
    public static string? GetString(JsonElement element, string propertyName)
    {
        return element.ValueKind == JsonValueKind.Object &&
               element.TryGetProperty(propertyName, out var property) &&
               property.ValueKind == JsonValueKind.String
            ? property.GetString()
            : null;
    }

    public static Guid? GetGuid(JsonElement element, string propertyName)
    {
        if (element.ValueKind != JsonValueKind.Object ||
            !element.TryGetProperty(propertyName, out var property))
            return null;

        return property.ValueKind == JsonValueKind.String && Guid.TryParse(property.GetString(), out var value)
            ? value
            : null;
    }

    public static IReadOnlyCollection<JsonElement> GetArray(JsonElement element, string propertyName)
    {
        if (element.ValueKind != JsonValueKind.Object ||
            !element.TryGetProperty(propertyName, out var property) ||
            property.ValueKind != JsonValueKind.Array)
            return [];

        return property.EnumerateArray().Select(item => item.Clone()).ToArray();
    }

    public static DateOnly? GetDateOnly(JsonElement element, string propertyName)
    {
        var value = GetString(element, propertyName);
        return DateOnly.TryParse(value, out var parsed) ? parsed : null;
    }

    public static TEnum GetEnum<TEnum>(JsonElement element, string propertyName, TEnum fallback)
        where TEnum : struct
    {
        var value = GetString(element, propertyName);
        return Enum.TryParse<TEnum>(value, true, out var parsed) ? parsed : fallback;
    }
}
