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

export function MaxDate(
  maxDate: Date | string | (() => Date),
  displayName?: string,
  validationOptions: ValidationOptions = {
    message: (args: ValidationArguments) => {
      if (typeof maxDate === 'function') maxDate = maxDate();

      return `Maior data permitida para ${
        displayName ?? `'${args.property}'`
      } é ${moment(maxDate).format('DD/MM/YYYY')}`;
    },
  },
) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      name: 'maxDate',
      target: object.constructor,
      propertyName: propertyName,
      constraints: ['maxDate'],
      options: validationOptions,
      validator: {
        validate(value: any) {
          if (typeof maxDate === 'function') maxDate = maxDate();

          const dateToValidate = moment(value).utc().startOf('day');

          const maxDateWithoutTime = moment(maxDate)
            .utc()
            .startOf('day')
            .toDate();

          return dateToValidate.isSameOrBefore(maxDateWithoutTime);
        },
      },
    });
  };
}
