package validation

import (
	"fmt"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v3"
)

var validate = validator.New(validator.WithRequiredStructEnabled())

// validateStruct runs tag-based validation and returns a Fiber 400 error on failure.
func validateStruct(payload any) error {
	if err := validate.Struct(payload); err != nil {
		if _, ok := err.(*validator.InvalidValidationError); ok {
			return fiber.NewError(fiber.StatusBadRequest, "invalid payload")
		}
		if verrs, ok := err.(validator.ValidationErrors); ok && len(verrs) > 0 {
			fe := verrs[0]
			field := strings.ToLower(fe.Field())
			msg := fmt.Sprintf("%s validation failed (%s)", field, fe.ActualTag())
			return fiber.NewError(fiber.StatusBadRequest, msg)
		}
		return fiber.NewError(fiber.StatusBadRequest, "validation failed")
	}
	return nil
}

func ValidateStruct(payload any) error {
	return validateStruct(payload)
}
