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

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

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

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

          const minDateWithoutTime = moment(minDate)
            .utc()
            .startOf('day')
            .toDate();

          return dateToValidate.isSameOrAfter(minDateWithoutTime);
        },
      },
    });
  };
}
