package com.nisemoe.nise.search

import jakarta.validation.Constraint
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import kotlin.reflect.KClass

@MustBeDocumented
@Constraint(validatedBy = [ChildQueriesDepthValidator::class])
@Target(allowedTargets = [AnnotationTarget.CLASS, AnnotationTarget.FIELD])
@Retention(AnnotationRetention.RUNTIME)
annotation class ValidChildQueriesDepth(
    val message: String = "Exceeds maximum depth of child queries",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Any>> = []
)

class ChildQueriesDepthValidator : ConstraintValidator<ValidChildQueriesDepth, List<SearchController.SearchQuery>> {

    override fun initialize(constraintAnnotation: ValidChildQueriesDepth?) {
        super.initialize(constraintAnnotation)
    }

    override fun isValid(queries: List<SearchController.SearchQuery>?, context: ConstraintValidatorContext): Boolean {
        return queries?.all { validateChildQueriesDepth(it, 1) } ?: true
    }

    private fun validateChildQueriesDepth(query: SearchController.SearchQuery, currentDepth: Int): Boolean {
        if (currentDepth > 10) return false
        query.childQueries?.forEach {
            if (!validateChildQueriesDepth(it, currentDepth + 1)) return false
        }
        return true
    }
}