package de.assecutor.pdftool.invoice;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Optional;

/**
 * Bean-Validation-Constraint für USt-IdNrn. Leere Werte gelten als gültig —
 * ob das Feld Pflicht ist, regeln {@code @NotBlank} bzw. die UI.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidVatId.Validator.class)
public @interface ValidVatId {

    String message() default "ungültige USt-IdNr.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<ValidVatId, String> {

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null || value.isBlank()) {
                return true;
            }
            Optional<String> error = VatIdValidator.validate(value);
            if (error.isPresent()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(error.get()).addConstraintViolation();
                return false;
            }
            return true;
        }
    }
}
