<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Utility;

/**
 * Utility methods for formatting duration values.
 *
 * @internal
 */
final class Duration {

  private function __construct() {}

  /**
   * Formats a duration in human-readable form from microseconds.
   *
   * @param int $microseconds
   *   Duration in microseconds.
   *
   * @return string
   *   Formatted duration string (e.g. "150µs", "2.5ms", "1.2s", "1m 30s").
   */
  public static function formatMicroseconds(int $microseconds): string {
    if ($microseconds < 1000) {
      return $microseconds . 'µs';
    }
    elseif ($microseconds < 1000000) {
      $milliseconds = $microseconds / 1000;
      if ($microseconds < 10000) {
        return round($milliseconds, 2) . 'ms';
      }
      elseif ($microseconds < 100000) {
        return round($milliseconds, 1) . 'ms';
      }
      return (int) round($milliseconds) . 'ms';
    }
    elseif ($microseconds < 10000000) {
      $seconds = $microseconds / 1000000;
      return round($seconds, 2) . 's';
    }
    elseif ($microseconds < 60000000) {
      $seconds = (int) floor($microseconds / 1000000);
      return $seconds . 's';
    }
    elseif ($microseconds < 3600000000) {
      $totalSeconds = (int) floor($microseconds / 1000000);
      $minutes = (int) floor($totalSeconds / 60);
      $secs = $totalSeconds % 60;
      return $secs > 0 ? "{$minutes}m {$secs}s" : "{$minutes}m";
    }
    else {
      $totalSeconds = (int) floor($microseconds / 1000000);
      $hours = (int) floor($totalSeconds / 3600);
      $minutes = (int) floor(($totalSeconds % 3600) / 60);
      return $minutes > 0 ? "{$hours}h {$minutes}m" : "{$hours}h";
    }
  }

}
