import { Injectable, Logger } from '@nestjs/common';
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
import { UserService } from 'modules/user/users.service';
import { UserRole } from 'common/enum/UserRole.enum';

@ValidatorConstraint({ name: 'ReferralMailValidator', async: true })
@Injectable()
export class ReferralMailValidator implements ValidatorConstraintInterface {
  private readonly logger = new Logger(ReferralMailValidator.name);
  constructor(private readonly userService: UserService) {}

  async validate(referralMail: string, args: ValidationArguments) {
    const { role } = args.object as { role: UserRole };

    this.logger.log(`Validating referral email ${referralMail} for role ${role}`);
    // Find referral user in the database
    const referralUser = await this.userService.findUserByEmail(referralMail);
    if (!referralUser) {
      this.logger.warn(`Referral email ${referralMail} not found`);
      return false;
    }

    // Ensure referral user has a superior role
    const roleHierarchy = [UserRole.USER, UserRole.ADMIN, UserRole.SUPER_ADMIN];
    return roleHierarchy.indexOf(referralUser.role) > roleHierarchy.indexOf(role);
  }

  defaultMessage() {
    return 'Referral email must belong to an existing user with a superior role.';
  }
}
