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

export function IsDefinedAllowingNull(validationOptions?: ValidationOptions) {
    return (object: unknown, propertyName: string) => {
        registerDecorator({
            options: validationOptions,
            propertyName,
            target: object?.constructor as (...args: any) => any,
            validator: IsDefinedAllowingNullConstraint,
        });
    };
}

@ValidatorConstraint({ name: 'IsDefinedAllowingNull' })
export class IsDefinedAllowingNullConstraint implements ValidatorConstraintInterface {
    validate(text: unknown) {
        return text !== undefined;
    }

    defaultMessage(args?: ValidationArguments): string {
        const propertyName = args?.property as string;
        return `${propertyName} must be different than undefined`;
    }
}
