<?php

declare(strict_types=1);

namespace Drupal\native_observability_dashboard\ValueObject;

/**
 * Represents a fixed dashboard time range.
 */
final class TimeRange {

  /**
   * Creates a new time range value object.
   *
   * @param int $startTimestamp
   *   The inclusive start timestamp.
   * @param int $endTimestamp
   *   The inclusive end timestamp.
   * @param string $label
   *   The human-readable range label.
   * @param string $key
   *   The machine-readable range key.
   */
  public function __construct(
    private readonly int $startTimestamp,
    private readonly int $endTimestamp,
    private readonly string $label,
    private readonly string $key = '30m',
  ) {
  }

  /**
   * Returns the range start timestamp.
   *
   * @return int
   *   The start timestamp.
   */
  public function getStartTimestamp(): int {
    return $this->startTimestamp;
  }

  /**
   * Returns the range end timestamp.
   *
   * @return int
   *   The end timestamp.
   */
  public function getEndTimestamp(): int {
    return $this->endTimestamp;
  }

  /**
   * Returns the range label.
   *
   * @return string
   *   The human-readable label.
   */
  public function getLabel(): string {
    return $this->label;
  }

  /**
   * Returns the machine-readable range key.
   *
   * @return string
   *   The range key.
   */
  public function getKey(): string {
    return $this->key;
  }

  /**
   * Returns the range duration in seconds.
   *
   * @return int
   *   The duration in seconds.
   */
  public function getDurationInSeconds(): int {
    return max(1, $this->endTimestamp - $this->startTimestamp);
  }

  /**
   * Creates the default last-30-minutes range.
   *
   * @return self
   *   The default dashboard range.
   */
  public static function createDefault(): self {
    $end = time();
    $start = $end - 1800;

    return new self($start, $end, 'Last 30 minutes', '30m');
  }

}
