import { describe, expect, test } from "bun:test";

import {
  formatCountdown,
  formatDurationUnit,
  formatRelativeTime,
  isOlderThan,
  subtractHours,
} from "../../../src/web/utils/time";

describe("subtractHours", () => {
  test("正常扣减小时", () => {
    const result = subtractHours(new Date("2025-01-15T12:00:00.000Z"), 3);

    expect(result.toISOString()).toBe("2025-01-15T09:00:00.000Z");
  });

  test("跨天扣减", () => {
    const result = subtractHours(new Date("2025-01-15T02:00:00.000Z"), 6);

    expect(result.toISOString()).toBe("2025-01-14T20:00:00.000Z");
  });

  test("跨月扣减", () => {
    const result = subtractHours(new Date("2025-03-01T01:00:00.000Z"), 2);

    expect(result.toISOString()).toBe("2025-02-28T23:00:00.000Z");
  });

  test("扣减 0 小时返回相同时间", () => {
    const result = subtractHours(new Date("2025-01-15T12:00:00.000Z"), 0);

    expect(result.toISOString()).toBe("2025-01-15T12:00:00.000Z");
  });
});

describe("formatRelativeTime", () => {
  const now = new Date("2025-01-01T00:02:00.000Z");

  test("格式化秒和分钟", () => {
    expect(formatRelativeTime("2025-01-01T00:01:45.000Z", now)).toBe("15秒前");
    expect(formatRelativeTime("2025-01-01T00:00:00.000Z", now)).toBe("2分钟前");
  });

  test("无时间返回占位", () => {
    expect(formatRelativeTime(null, now)).toBe("尚无检查数据");
    expect(formatRelativeTime("invalid", now)).toBe("尚无检查数据");
  });
});

describe("formatDurationUnit", () => {
  test("按秒、分钟、小时动态格式化", () => {
    expect(formatDurationUnit(1500)).toEqual({ suffix: "秒", value: 1.5 });
    expect(formatDurationUnit(120000)).toEqual({ suffix: "分钟", value: 2 });
    expect(formatDurationUnit(5400000)).toEqual({ suffix: "小时", value: 1.5 });
  });

  test("空时长返回占位", () => {
    expect(formatDurationUnit(null)).toEqual({ suffix: "", value: 0 });
  });
});

describe("formatCountdown", () => {
  test("格式化秒级和分钟级倒计时", () => {
    expect(formatCountdown(0)).toBe("0秒");
    expect(formatCountdown(59)).toBe("59秒");
    expect(formatCountdown(60)).toBe("1分0秒");
    expect(formatCountdown(299)).toBe("4分59秒");
  });
});

describe("isOlderThan", () => {
  test("判断时间是否超过阈值", () => {
    const now = new Date("2025-01-01T00:02:00.000Z");

    expect(isOlderThan("2025-01-01T00:00:59.000Z", 60000, now)).toBe(true);
    expect(isOlderThan("2025-01-01T00:01:30.000Z", 60000, now)).toBe(false);
  });
});
