//! The single wall-clock surface — one canonical `now_ms()`.
//!
//! Across the workspace a dozen modules each grew their own private
//! `now_ms()` that read `SystemTime::now()`, subtracted `UNIX_EPOCH`, and
//! returned the elapsed milliseconds — the `Date.now()` analogue the TS sources
//! lean on. They drifted in return type (`f64` here, `i64` there, `u64`
//! elsewhere) and in how they clamp a pre-epoch clock. This module collapses
//! all of that into one place so the clock-read logic lives once.
//!
//! The canonical return is [`u64`] — it matches the majority of call sites and
//! is the natural type for an always-non-negative epoch-millisecond count. The
//! few `f64`/`i64` consumers cast the `u64` at their own boundary (the value is
//! well within the lossless range of both for any realistic clock).

use std::time::{SystemTime, UNIX_EPOCH};

/// Current wall-clock time in whole epoch milliseconds — the canonical
/// `Date.now()` analogue.
///
/// A clock set before the Unix epoch (or any `duration_since` error) clamps to
/// `0` rather than producing a wrapped or negative timestamp, matching the
/// defensive `.unwrap_or(0)` every former local copy used.
#[inline]
#[must_use]
pub fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn now_ms_is_after_a_known_past_epoch() {
        // 2020-01-01T00:00:00Z in epoch millis — any real clock is well past it.
        const Y2020_MS: u64 = 1_577_836_800_000;
        assert!(
            now_ms() > Y2020_MS,
            "now_ms() should be a present-day epoch-millisecond value"
        );
    }

    #[test]
    fn now_ms_is_monotonic_nondecreasing_in_practice() {
        let first = now_ms();
        let second = now_ms();
        assert!(
            second >= first,
            "two back-to-back reads must not go backwards: {first} then {second}"
        );
    }
}
