package org.octopus.internal.web.dtos.validators

import jakarta.validation.Constraint
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import jakarta.validation.Payload
import org.octopus.internal.common.enums.EEntryType
import kotlin.reflect.KClass


class EntryTypeValidator : ConstraintValidator<EntryTypeValidator.Validate, String> {
    override fun isValid(value: String, context: ConstraintValidatorContext): Boolean {
        val typeNames = EEntryType.entries.map {e -> e.name}
        val matchedType = typeNames.any { e -> e == value }

        if (!matchedType) {
            context.disableDefaultConstraintViolation()
            context.buildConstraintViolationWithTemplate("Invalid. '$value' is not in accepted values: $typeNames")
                .addConstraintViolation()
        }

        return matchedType
    }

    @Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
    @Retention(AnnotationRetention.RUNTIME)
    @MustBeDocumented
    @Constraint(validatedBy = [EntryTypeValidator::class])
    annotation class Validate(
        val message: String = "",
        val groups: Array<KClass<*>> = [],
        val payload: Array<KClass<out Payload>> = []
    )
}