using System;

namespace Common.Util
{
    /// <summary>
    /// 时间戳转换辅助类
    /// </summary>
    public static class TimestampHelper
    {
        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        /// <summary>
        /// 将DateTime转换为毫秒时间戳（UTC）
        /// </summary>
        /// <param name="dateTime">DateTime对象</param>
        /// <returns>毫秒时间戳，如果输入为null则返回null</returns>
        public static long? ToTimestamp(this DateTime? dateTime)
        {
            if (!dateTime.HasValue)
            {
                return null;
            }
            return ToTimestamp(dateTime.Value);
        }

        /// <summary>
        /// 将DateTime转换为毫秒时间戳（UTC）
        /// </summary>
        /// <param name="dateTime">DateTime对象</param>
        /// <returns>毫秒时间戳</returns>
        public static long ToTimestamp(this DateTime dateTime)
        {
            var utcDateTime = dateTime.Kind == DateTimeKind.Unspecified 
                ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) 
                : dateTime.ToUniversalTime();
            return (long)(utcDateTime - Epoch).TotalMilliseconds;
        }

        /// <summary>
        /// 将毫秒时间戳转换为DateTime（UTC）
        /// </summary>
        /// <param name="timestamp">毫秒时间戳</param>
        /// <returns>DateTime对象，如果输入为null则返回null</returns>
        public static DateTime? ToDateTime(this long? timestamp)
        {
            if (!timestamp.HasValue)
            {
                return null;
            }
            return ToDateTime(timestamp.Value);
        }

        /// <summary>
        /// 将毫秒时间戳转换为DateTime（UTC）
        /// </summary>
        /// <param name="timestamp">毫秒时间戳</param>
        /// <returns>DateTime对象</returns>
        public static DateTime ToDateTime(this long timestamp)
        {
            return Epoch.AddMilliseconds(timestamp);
        }
    }
}
