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

@ValidatorConstraint()
export class IsRoleAuthorData implements ValidatorConstraintInterface {
  propertyName: string;
  constructor(propertyName: string) {
    this.propertyName = propertyName;
  }

  validate(value: any, args: ValidationArguments): boolean {
    const request = args.object as SignupRequest | PostUpdateUserRequest;
    const { role } = request;
    if (role === USER_ROLES.AUTHOR && value === undefined) {
      return false;
    }
    return true;
  }
  defaultMessage(): string {
    return `When role is author, ${this.propertyName} cannot be undefined`;
  }
}

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: new IsRoleAuthorData(propertyName),
    });
  };
};
