import {
  registerDecorator,
  ValidationArguments,
  ValidationOptions,
} from 'class-validator';
import { SignupRequest } from '../../features/users/types/types';

export const IsPasswordvalid = (validationOptions?: ValidationOptions) => {
  return (object: any, propertyName: string) => {
    registerDecorator({
      name: 'IsPasswordvalid',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate: (value: string | undefined) => {
          // passwordが設定されていない場合はチェックしない
          if (value === undefined) {
            return true;
          }
          // 正規表現でパスワードのチェックを行う
          // 4～16文字の半角英数字と記号のみ
          const regex = /^[!-~]{4,16}$/;
          if (!regex.test(value)) {
            return false;
          }

          return true;
        },
        defaultMessage: () => {
          return 'EncryptionPassword rule not satisfied';
        },
      },
    });
  };
};

export const IsEncryptionPasswordPresent = (
  validationOptions?: ValidationOptions,
) => {
  return (object: SignupRequest, propertyName: string) => {
    registerDecorator({
      name: 'IsEncryptionPasswordValid',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate: (value: string | undefined, args: ValidationArguments) => {
          const { encryption } = args.object as SignupRequest;
          if (encryption === true && !value) {
            return false;
          }
          return true;
        },
        defaultMessage: () => {
          return 'Encryption password is required when encryption is enabled';
        },
      },
    });
  };
};
