import { Injectable } from "@nestjs/common";
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
import { Role } from "src/database/models/role.model";

@ValidatorConstraint({ name: 'IsExistRole', async: true })
@Injectable()
export class IsExistRoleRule implements ValidatorConstraintInterface {
    async validate(roleId: number): Promise<boolean> {
        return await Role.findByPk(roleId).then(role => {
            return role
        }) !== null
    }

    defaultMessage() {
        return `Role tidak ditemukan`;
    }
}

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