import {Injectable, UnprocessableEntityException} from '@nestjs/common';
import {PrismaService} from "../prisma/prisma.service";
import {
    registerDecorator,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface,
} from 'class-validator';
import {PrismaClient} from "@prisma/client";

export function isEmailUnique(validationOptions?: ValidationOptions) {
    return function (object: any, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            validator: CustomEmailvalidation,
        });
    };
}

@ValidatorConstraint({name: 'email', async: true})
@Injectable()
export class CustomEmailvalidation implements ValidatorConstraintInterface {
    constructor(private readonly prisma: PrismaService) {
    }

    async validate(value: string): Promise<boolean> {
        const pr = new PrismaClient();
        return pr.user
            .findFirst({where: {email: value}})
            .then((user) => {
                if (user) {
                    throw new UnprocessableEntityException('Email already exists');
                } else {
                    return true;
                }
            });
    }
}


// Phone Number

export function isPhoneUnique(validationOptions?: ValidationOptions) {
    return function (object: any, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            validator: CustomPhonevalidation,
        });
    };
}

@ValidatorConstraint({name: 'phone', async: true})
@Injectable()
export class CustomPhonevalidation implements ValidatorConstraintInterface {
    constructor(private readonly prisma: PrismaService) {
    }

    async validate(value: string): Promise<boolean> {
        const pr = new PrismaClient();
        return pr.user
            .findFirst({where: {phone: value}})
            .then((user) => {
                if (user) {
                    throw new UnprocessableEntityException('Phone already exists');
                } else {
                    return true;
                }
            });
    }
}
