export type ElementEditorValidationMessages = {
  required?: string;
  variationRequired?: string;
  invalidNumber?: string;
};

const isBlank = (value: unknown): boolean => typeof value !== 'string' || value.trim().length === 0;

export function validateElementEditorValues(
  values: any,
  messages: ElementEditorValidationMessages = {},
): Record<string, string> {
  const required = messages.required ?? 'This field is required';
  const variationRequired = messages.variationRequired ?? 'At least one variation is required';
  const invalidNumber = messages.invalidNumber ?? 'Enter a valid number';
  const errors: Record<string, string> = {};

  if (isBlank(values?.name)) errors.name = required;

  const variations = Array.isArray(values?.variations) ? values.variations : [];
  if (variations.length === 0) errors.variations = variationRequired;

  variations.forEach((variation: any, index: number) => {
    if (isBlank(variation?.id)) errors[`variations[${index}].id`] = required;
    if (isBlank(variation?.name)) errors[`variations[${index}].name`] = required;
    const price = variation?.price;
    if (price !== null && price !== undefined && (String(price).trim() === '' || !Number.isFinite(Number(price)))) {
      errors[`variations[${index}].price`] = invalidNumber;
    }
  });

  return errors;
}
