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

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

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

    defaultMessage() {
        return `Nomor HP telah digunakan`;
    }
}

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