import { describe, expect, it } from "vitest";
import { isDefined, parseDate, sleep, slugify } from "./index.js";

describe("parseDate", () => {
  it("should return undefined for null or undefined", () => {
    expect(parseDate(null)).toBeUndefined();
    expect(parseDate(undefined)).toBeUndefined();
  });

  it("should return the same Date object if passed a Date", () => {
    const date = new Date("2024-01-15");
    expect(parseDate(date)).toBe(date);
  });

  it("should parse valid date strings", () => {
    const result = parseDate("2024-01-15");
    expect(result).toBeInstanceOf(Date);
    expect(result?.toISOString()).toContain("2024-01-15");
  });

  it("should return undefined for invalid date strings", () => {
    expect(parseDate("not-a-date")).toBeUndefined();
  });
});

describe("slugify", () => {
  it("should convert text to lowercase slug", () => {
    expect(slugify("Hello World")).toBe("hello-world");
  });

  it("should handle special characters", () => {
    expect(slugify("Hello, World!")).toBe("hello-world");
  });

  it("should trim leading and trailing hyphens", () => {
    expect(slugify("  Hello World  ")).toBe("hello-world");
  });

  it("should handle empty string", () => {
    expect(slugify("")).toBe("");
  });

  it("should handle string with only whitespace", () => {
    expect(slugify("   ")).toBe("");
  });

  it("should handle consecutive special characters", () => {
    expect(slugify("Hello---World")).toBe("hello-world");
    expect(slugify("Hello___World")).toBe("hello-world");
    expect(slugify("Hello   World")).toBe("hello-world");
  });

  it("should handle numbers", () => {
    expect(slugify("Product 123")).toBe("product-123");
    expect(slugify("2024 New Year")).toBe("2024-new-year");
  });

  it("should handle mixed case", () => {
    expect(slugify("HeLLo WoRLd")).toBe("hello-world");
  });

  it("should remove leading/trailing special chars", () => {
    expect(slugify("---Hello World---")).toBe("hello-world");
    expect(slugify("!@#Hello World!@#")).toBe("hello-world");
  });

  it("should handle string with only special characters", () => {
    expect(slugify("!@#$%^&*()")).toBe("");
  });
});

describe("sleep", () => {
  it("should resolve after the specified time", async () => {
    const start = Date.now();
    await sleep(50);
    const elapsed = Date.now() - start;
    expect(elapsed).toBeGreaterThanOrEqual(45);
  });
});

describe("isDefined", () => {
  it("should return false for null and undefined", () => {
    expect(isDefined(null)).toBe(false);
    expect(isDefined(undefined)).toBe(false);
  });

  it("should return true for defined values", () => {
    expect(isDefined(0)).toBe(true);
    expect(isDefined("")).toBe(true);
    expect(isDefined(false)).toBe(true);
    expect(isDefined({})).toBe(true);
  });
});
