import { describe, expect, it } from "vitest";
import {
  compareNullableValues,
  sortItems,
  toggleSort,
} from "../../../../common/core/utils/sort";

describe("common sort utilities in devfront coverage", () => {
  it("keeps nullish values last and compares normalized primitive values", () => {
    expect(compareNullableValues(null, "alpha", "asc")).toBe(1);
    expect(compareNullableValues("alpha", undefined, "asc")).toBe(-1);
    expect(compareNullableValues("Beta", "alpha", "asc")).toBe(1);
    expect(compareNullableValues("Beta", "alpha", "desc")).toBe(-1);
    expect(compareNullableValues(true, false, "asc")).toBe(1);
    expect(
      compareNullableValues(
        new Date("2026-05-02T00:00:00Z"),
        new Date("2026-05-01T00:00:00Z"),
        "asc",
      ),
    ).toBe(1);
  });

  it("toggles sort direction and sorts with default and custom resolvers", () => {
    const firstSort = toggleSort(null, "name");
    expect(firstSort).toEqual({ key: "name", direction: "asc" });
    expect(toggleSort(firstSort, "name")).toEqual({
      key: "name",
      direction: "desc",
    });
    expect(toggleSort(firstSort, "createdAt")).toEqual({
      key: "createdAt",
      direction: "asc",
    });

    const rows = [
      { name: "charlie", rank: 3, nested: { score: 20 } },
      { name: "Alpha", rank: 1, nested: { score: 30 } },
      { name: "bravo", rank: 2, nested: { score: 10 } },
    ];

    expect(
      sortItems(rows, { key: "name", direction: "asc" }).map(
        (row) => row.name,
      ),
    ).toEqual(["Alpha", "bravo", "charlie"]);
    expect(
      sortItems(rows, { key: "score", direction: "desc" }, {
        score: (row) => row.nested.score,
      }).map((row) => row.name),
    ).toEqual(["Alpha", "charlie", "bravo"]);
    expect(sortItems(rows, null)).not.toBe(rows);
  });
});
