namespace Sonex.Services.ImageSync;

internal static class DatabaseTime
{
    private static readonly TimeZoneInfo DatabaseTimeZone = ResolveTimeZone();

    public static DateTime Now()
    {
        return FromUtc(DateTime.UtcNow);
    }

    public static DateTime FromUtc(DateTime utcDateTime)
    {
        DateTime normalizedUtc = utcDateTime.Kind switch
        {
            DateTimeKind.Utc => utcDateTime,
            DateTimeKind.Local => utcDateTime.ToUniversalTime(),
            _ => DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc)
        };

        DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(normalizedUtc, DatabaseTimeZone);
        return DateTime.SpecifyKind(localTime, DateTimeKind.Unspecified);
    }

    private static TimeZoneInfo ResolveTimeZone()
    {
        try
        {
            return TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
        }
        catch (TimeZoneNotFoundException)
        {
            return TimeZoneInfo.Local;
        }
        catch (InvalidTimeZoneException)
        {
            return TimeZoneInfo.Local;
        }
    }
}
