import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';
import { Assignee } from '../../features/tasks/types/types';

@ValidatorConstraint()
export class IsTypist implements ValidatorConstraintInterface {
  validate(values: Assignee[]): boolean {
    if (!values) {
      return false;
    }

    return values.every((value) => {
      const { typistUserId, typistGroupId, typistName } = value;
      if (typistUserId === undefined && typistGroupId === undefined) {
        return false;
      }
      if (typistUserId !== undefined && typistGroupId !== undefined) {
        return false;
      }
      if (!typistName) {
        return false;
      }
      return true;
    });
  }
  defaultMessage(): string {
    return 'Request body is invalid format';
  }
}

/**
 * Validations options
 * @param [validationOptions]
 * @returns
 */
export const IsAssignees = (validationOptions?: ValidationOptions) => {
  return (object: any, propertyName: string) => {
    registerDecorator({
      name: 'IsAssignees',
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      validator: IsTypist,
    });
  };
};
