import {
  registerDecorator,
  type ValidationArguments,
  type ValidationOptions,
} from 'class-validator';

// The description column stores JSON, so the editor may send either plain
// text/HTML (what multipart form data always sends) or a rich-text document
// object. Both are accepted; only empty values are rejected.
export function isEditorContent(value: unknown): boolean {
  if (typeof value === 'string') {
    return value.trim() !== '';
  }

  // A rich-text document is a plain object, never an array.
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

export function IsEditorContent(options?: ValidationOptions) {
  return function (target: object, propertyName: string) {
    registerDecorator({
      name: 'isEditorContent',
      target: target.constructor,
      propertyName,
      options,
      validator: {
        validate: (value: unknown) => isEditorContent(value),
        defaultMessage: (args: ValidationArguments) =>
          `${args.property} must be non-empty text or a rich-text object`,
      },
    });
  };
}
