import { Transform } from 'class-transformer';
import { Matches } from 'class-validator';

export const DECIMAL_PATTERN = /^-?\d+(?:\.\d+)?$/;

export function DecimalString(): PropertyDecorator {
  return function decimalStringDecorator(target: object, propertyKey: string | symbol): void {
    Transform(({ value }) => (value === null || value === undefined ? value : String(value)))(
      target,
      propertyKey,
    );
    Matches(DECIMAL_PATTERN, {
      message: `${String(propertyKey)} must be a plain decimal value`,
    })(target, propertyKey);
  };
}
