import { sleep } from '@enbox/common';
import { Temporal } from '@js-temporal/polyfill';
import { DwnError, DwnErrorCode } from '../core/dwn-error.js';
/**
 * Time related utilities.
 */
export class Time {
    /**
     * We must sleep for at least 2ms to avoid timestamp collisions during testing.
     * https://github.com/enboxorg/enbox/issues/481
     *
     * For arbitrary-duration sleeps, use `sleep` from `@enbox/common`
     * directly — this class only retains the DWN-specific minimum.
     */
    static async minimalSleep() {
        await sleep(2);
    }
    /**
     * Returns an UTC ISO-8601 timestamp with microsecond precision accepted by DWN.
     * using @js-temporal/polyfill
     */
    static getCurrentTimestamp() {
        return Temporal.Now.instant().toString({ smallestUnit: 'microseconds' });
    }
    /**
     * Creates a UTC ISO-8601 timestamp in microsecond precision accepted by DWN.
     * @param options - Options for creating the timestamp.
     * @returns string
     */
    static createTimestamp(options) {
        const { year, month, day, hour, minute, second, millisecond, microsecond } = options;
        return Temporal.ZonedDateTime.from({
            timeZone: 'UTC',
            year,
            month,
            day,
            hour,
            minute,
            second,
            millisecond,
            microsecond
        }).toInstant().toString({ smallestUnit: 'microseconds' });
    }
    /**
     * Creates a UTC ISO-8601 timestamp offset from now or given timestamp accepted by DWN.
     * @param offset Negative number means offset into the past.
     */
    static createOffsetTimestamp(offset, timestamp) {
        const timestampInstant = timestamp ? Temporal.Instant.from(timestamp) : Temporal.Now.instant();
        const offsetDuration = Temporal.Duration.from(offset);
        const offsetInstant = timestampInstant.add(offsetDuration);
        return offsetInstant.toString({ smallestUnit: 'microseconds' });
    }
    /**
     * Validates that the provided timestamp is a valid number
     * @param timestamp the timestamp to validate
     * @throws DwnError if timestamp is not a valid number
     */
    static validateTimestamp(timestamp) {
        try {
            Temporal.Instant.from(timestamp);
        }
        catch {
            throw new DwnError(DwnErrorCode.TimestampInvalid, `Invalid timestamp: ${timestamp}`);
        }
    }
}
//# sourceMappingURL=time.js.map