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

export interface StateFilterCapability {
  fieldName: string;
  states: Array<{ value: string; label: string }>;
}

function stateLabel(value: string): string {
  if (value.includes("/")) {
    return value.split("/").pop() ?? value;
  }
  return value;
}

function resolveStateFieldName(entity: EntityDescription): string | undefined {
  const typeName = entity.typeName ?? "";
  const fields = entity.fields ?? [];
  const byName = new Map(
    fields
      .filter((f) => f.name?.trim())
      .map((f) => [f.name!, f] as const),
  );

  if (byName.has("State")) return "State";

  const typeState = `${typeName}State`;
  if (byName.has(typeState)) return typeState;

  const stateField = fields.find(
    (f) =>
      f.name?.endsWith("State") &&
      f.type === "Entity" &&
      f.filterable !== false,
  );
  return stateField?.name;
}

export function detectStateFilterCapability(
  entity: EntityDescription,
): StateFilterCapability | null {
  const validStates = entity.validStates?.filter((s) => s.trim()) ?? [];
  if (validStates.length === 0) return null;

  const fieldName = resolveStateFieldName(entity);
  if (!fieldName) return null;

  return {
    fieldName,
    states: validStates.map((value) => ({
      value,
      label: stateLabel(value),
    })),
  };
}
