package com.qqchen.deploy.backend.framework.utils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class DateUtils {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String formatMillis(long millis) {
        return formatMillis(millis, DEFAULT_PATTERN);
    }

    public static String formatMillis(long millis, String pattern) {
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static LocalDateTime toLocalDateTime(long millis) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
    }

     /**
      * Format a duration in milliseconds to HH:mm:ss (zero-padded).
      * Example: 159000 -> 00:02:39
      */
     public static String formatDurationHMS(long millis) {
         if (millis < 0) millis = 0;
         long totalSeconds = millis / 1000L;
         long hours = totalSeconds / 3600L;
         long minutes = (totalSeconds % 3600L) / 60L;
         long seconds = totalSeconds % 60L;
         return String.format("%02d:%02d:%02d", hours, minutes, seconds);
     }

     /**
      * Format a duration in seconds to HH:mm:ss (zero-padded).
      */
     public static String formatDurationHMSBySeconds(long seconds) {
         if (seconds < 0) seconds = 0;
         long hours = seconds / 3600L;
         long minutes = (seconds % 3600L) / 60L;
         long sec = seconds % 60L;
         return String.format("%02d:%02d:%02d", hours, minutes, sec);
     }

     /**
      * 格式化 LocalDateTime 为默认格式 (yyyy-MM-dd HH:mm:ss)
      *
      * @param dateTime 日期时间对象
      * @return 格式化后的字符串，如果为 null 则返回 "N/A"
      */
     public static String format(LocalDateTime dateTime) {
         if (dateTime == null) {
             return "N/A";
         }
         return dateTime.format(DateTimeFormatter.ofPattern(DEFAULT_PATTERN));
     }

     /**
      * 格式化 LocalDateTime 为指定格式
      *
      * @param dateTime 日期时间对象
      * @param pattern  日期格式模板
      * @return 格式化后的字符串，如果为 null 则返回 "N/A"
      */
     public static String format(LocalDateTime dateTime, String pattern) {
         if (dateTime == null) {
             return "N/A";
         }
         return dateTime.format(DateTimeFormatter.ofPattern(pattern));
     }
}
