import { describe, expect, it } from "vitest";
import { formatTimeAgo, normalizeUnixNano } from "./time";

const NOW_NANO = 1_800_000_000_000_000_000; // 2027-01-15T08:00:00Z, in nanoseconds

describe("normalizeUnixNano", () => {
  it("accepts seconds, milliseconds, and nanoseconds", () => {
    expect(normalizeUnixNano(1_800_000_000)).toBe(NOW_NANO);
    expect(normalizeUnixNano(1_800_000_000_000)).toBe(NOW_NANO);
    expect(normalizeUnixNano(NOW_NANO)).toBe(NOW_NANO);
  });

  it("treats blank and nullish input as absent", () => {
    expect(normalizeUnixNano(null)).toBeNull();
    expect(normalizeUnixNano(undefined)).toBeNull();
    expect(normalizeUnixNano("")).toBeNull();
    expect(normalizeUnixNano("   ")).toBeNull();
  });
});

// Every other formatter normalized its input, so a seconds-precision timestamp from the backend
// showed up here as decades in the past rather than minutes.
describe("formatTimeAgo", () => {
  it("gives the same answer whichever precision the timestamp arrives in", () => {
    const tenMinutesAgoNano = NOW_NANO - 10 * 60 * 1_000_000_000;
    const expected = formatTimeAgo(tenMinutesAgoNano, NOW_NANO);

    expect(formatTimeAgo(tenMinutesAgoNano / 1_000_000, NOW_NANO)).toBe(expected);
    expect(formatTimeAgo(tenMinutesAgoNano / 1_000_000_000, NOW_NANO)).toBe(expected);
    expect(expected).not.toBe("—");
  });

  it("still reports very recent timestamps as just now", () => {
    expect(formatTimeAgo(NOW_NANO - 1_000_000_000, NOW_NANO)).toBe(
      formatTimeAgo(NOW_NANO, NOW_NANO),
    );
  });

  it("returns a placeholder for missing timestamps", () => {
    expect(formatTimeAgo(null, NOW_NANO)).toBe("—");
    expect(formatTimeAgo(0, NOW_NANO)).toBe("—");
  });
});
