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

export const IsRoleAuthorDataValid = <
  T extends SignupRequest | PostUpdateUserRequest,
>(
  validationOptions?: ValidationOptions,
) => {
  return (object: T, propertyName: string) => {
    registerDecorator({
      name: 'IsRoleAuthorDataValid',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate: (value: any, args: ValidationArguments) => {
          const request = args.object as T;
          const { role } = request;
          if (role === USER_ROLES.AUTHOR && value === undefined) {
            return false;
          }
          return true;
        },
        defaultMessage: () => {
          return `When role is author, ${propertyName} cannot be undefined`;
        },
      },
    });
  };
};
