import { Injectable } from "@nestjs/common";
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
import { UsersService } from "src/modules/users/users.service";

@ValidatorConstraint({ name: 'IsUserEmailUnique', async: true })
@Injectable()
export class IsUserEmailUniqueRule implements ValidatorConstraintInterface {
    constructor(private readonly usersService: UsersService) {}

    async validate(email: string): Promise<boolean> {
        return await this.usersService.findBy({
            email: email,
            active: true
        }) === null
    }

    defaultMessage() {
        return `Email telah digunakan`;
    }
}

export function IsUserEmailUnique(validationOptions?: ValidationOptions) {
    return function (object: any, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [],
            validator: IsUserEmailUniqueRule,
        })
    }
}