import type {
  FieldSpec,
  NonReferenceField,
  StringLengthRange,
} from '../../types/SchemaConfig';
import type { FieldProperties, FieldRules } from './types';

export const toFieldSpec = (
  properties: FieldProperties,
  rules: FieldRules,
): FieldSpec => {
  const { type, name, isPii, helpText } = properties;
  const { validationRules } = rules;
  const trimmedHelpText = helpText.trim();

  const hasRules =
    validationRules.required !== undefined ||
    validationRules.charactersLimit !== undefined;

  const validation: NonReferenceField['validation'] = hasRules
    ? {
        required: Boolean(validationRules.required),
        ...(validationRules.charactersLimit !== undefined && {
          stringLengthRange:
            validationRules.charactersLimit as StringLengthRange,
        }),
      }
    : undefined;

  return {
    type,
    displayName: name.trim(),
    ...(isPii && { isPii: true }),
    ...(trimmedHelpText && { helpText: trimmedHelpText }),
    ...(validation && { validation }),
  };
};
