import { expect, test } from "vitest";
import { groupDefinitions } from "./group-fields";
import type { components } from "../api/schema";

type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
type MinDef = Pick<FieldDefinitionView, "key" | "group">;

const def = (key: string, group: string | null): MinDef => ({
  key,
  group: group as FieldDefinitionView["group"],
});

function keysByGroup(defs: MinDef[]) {
  return groupDefinitions(defs as FieldDefinitionView[], "Other").map((g) => ({
    group: g.group,
    keys: g.defs.map((d) => d.key),
  }));
}

test("preserves definition order within and across groups; Other is last", () => {
  const result = keysByGroup([
    def("a", "Description"),
    def("b", null),
    def("c", "Description"),
    def("d", "Provenance"),
    def("e", "  "),
  ]);

  expect(result).toEqual([
    { group: "Description", keys: ["a", "c"] },
    { group: "Provenance", keys: ["d"] },
    { group: "Other", keys: ["b", "e"] },
  ]);
});

test("all-ungrouped → a single trailing Other group", () => {
  expect(keysByGroup([def("x", null), def("y", null)])).toEqual([
    { group: "Other", keys: ["x", "y"] },
  ]);
});
