import type { EntityDescription } from "@arco/clarizen-lib";

const FALLBACK_FIELDS = ["Name", "Title", "Subject", "Description"] as const;

const NON_QUERYABLE = new Set(["id", "Id", "ID"]);

export function resolveDisplayField(entity: EntityDescription): string {
  const fieldNames = new Set(
    (entity.fields ?? [])
      .map((f) => f.name)
      .filter((name): name is string => Boolean(name?.trim())),
  );

  const candidates = [
    entity.displayField,
    ...FALLBACK_FIELDS,
  ].filter((name): name is string => Boolean(name?.trim()));

  for (const candidate of candidates) {
    if (NON_QUERYABLE.has(candidate)) continue;
    if (fieldNames.size === 0 || fieldNames.has(candidate)) {
      return candidate;
    }
  }

  return "Name";
}
