using System.Globalization;

namespace Predictalytics.Infrastructure.Helpers;

/// <summary>
/// Parses timestamp strings from platform APIs as UTC.
/// <para>
/// The platforms deliver ISO-8601 strings; the domain stores UTC throughout — every call
/// site falls back to <see cref="DateTime.UtcNow"/>, and the neighbouring DbCreatedAt is
/// always UTC. A plain <c>DateTime.TryParse</c> breaks that in two ways: it honours the
/// machine's locale, and it converts a "Z"-suffixed timestamp to <em>local</em> time. The
/// same API payload would therefore land in the database differently on a Berlin
/// workstation than on a UTC server.
/// </para>
/// </summary>
public static class DateParsing
{
    private const DateTimeStyles UtcStyles =
        DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal;

    /// <summary>
    /// Parses an API timestamp as UTC. Returns null when absent or unparseable.
    /// Timestamps without a zone designator are treated as UTC.
    /// </summary>
    public static DateTime? ParseUtc(string? value) =>
        DateTime.TryParse(value, CultureInfo.InvariantCulture, UtcStyles, out var parsed)
            ? parsed
            : null;

    /// <summary>
    /// Parses an API timestamp as UTC, falling back to the current UTC time.
    /// </summary>
    public static DateTime ParseUtcOrNow(string? value) => ParseUtc(value) ?? DateTime.UtcNow;
}
