import {
  ValidationArguments,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
  registerDecorator,
} from "class-validator"
import { REQUEST_CONTEXT } from "../interceptors/inject-request.interceptor"
import { Injectable } from "@nestjs/common"
import { isEmpty } from "../../utils/helpers"
import { AuthRepository } from "../../modules/auth/repositories/auth.repository"

@ValidatorConstraint({ async: true })
@Injectable()
export class IsExistsConstraint implements ValidatorConstraintInterface {
  constructor(private readonly authRepository: AuthRepository) {}

  async validate(value: any, args: ValidationArguments) {
    const [modelName, property, compareWithFieldValue] = args.constraints
    let id
    let propertyValue
    let result

    if (compareWithFieldValue) {
      propertyValue = value
    } else {
      id = args?.object[REQUEST_CONTEXT]?.id || ""
      propertyValue = id
    }

    if (isEmpty(propertyValue)) {
      return true
    }

    const params = { where: {} }
    params["where"][property] = propertyValue
    console.log("params================", params)
    if (modelName == "user")
      result = await this.authRepository.getByParams(params)

    return result.length !== 0
  }
}

export const IsExists = (
  modelName: "user" | "brand",
  property: string,
  compareWithFieldValue: boolean,
  validationOptions?: ValidationOptions,
) => {
  return function (object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [modelName, property, compareWithFieldValue],
      validator: IsExistsConstraint,
    })
  }
}
