import { UnprocessableEntityException, ValidationError } from "@nestjs/common"
import { code } from "./response.code"
import { messageKey } from "../../constants/message-keys"
import { validationMessage } from "../../utils/helpers"

export const validationError = (errors: ValidationError[]) => {
  const errorData = []

  errors.map((error) => {
    if (error.constraints) {
      const firstConstraintKey = Object.keys(error.constraints)[0]
      errorData.push({
        ":field": error.property,
        type: firstConstraintKey,
        message: error.constraints[firstConstraintKey],
      })
    } else if (error.children && error.children.length > 0) {
      // If it's an array validation error, process each child error
      error.children.map((subError, index) => {
        if (subError.children && subError.children.length > 0) {
          subError.children.map((subChildError, subChildIndex) => {
            if (subChildError.children && subChildError.children.length > 0) {
              subChildError.children.map((nestedSubChildError) => {
                const firstConstraintKey = Object.keys(
                  nestedSubChildError.constraints,
                )[0]
                errorData.push({
                  ":field": `${error.property}.${subError.property}.${subChildIndex}.${nestedSubChildError.property}.${nestedSubChildError.property}`,
                  type: firstConstraintKey,
                  message: nestedSubChildError.constraints[firstConstraintKey],
                })
              })
            } else {
              const firstConstraintKey = Object.keys(
                subChildError.constraints,
              )[0]
              errorData.push({
                ":field": `${error.property}.${index}.${subChildError.property}`,
                type: firstConstraintKey,
                message: subChildError.constraints[firstConstraintKey],
              })
            }
          })
        } else {
          const firstConstraintKey = Object.keys(subError.constraints)[0]
          errorData.push({
            ":field": `${error.property}.${subError.property}`,
            type: firstConstraintKey,
            message: subError.constraints[firstConstraintKey],
          })
        }
      })
    }
  })

  const validationErrorResponse: any = {
    success: false,
    message: validationMessage(messageKey.validation_error),
    status: code.VALIDATION,
    errors: errorData,
  }

  throw new UnprocessableEntityException(validationErrorResponse)
}
