package jdenticon

import (
	"gitea.dockr.co/kev/go-jdenticon/internal/engine"
)

// validation.go contains helper functions for input validation and DoS protection.

// validateInputs performs common validation for input string and size parameters.
// This provides centralized validation logic used across all public API functions.
func validateInputs(input string, size int, config Config) error {
	// Validate input string length
	if maxLen := config.effectiveMaxInputLength(); maxLen != -1 && len(input) > maxLen {
		return NewErrValueTooLarge("InputLength", maxLen, len(input))
	}

	// Validate that input is not empty
	if input == "" {
		return NewErrInvalidInput("input", input, "cannot be empty")
	}

	// Validate base icon size (must be positive)
	if size <= 0 {
		return ErrInvalidSize(size)
	}

	// Validate icon size against configured limit
	if maxSize := config.effectiveMaxIconSize(); maxSize != -1 && size > maxSize {
		return NewErrValueTooLarge("IconSize", maxSize, size)
	}

	return nil
}

// validateComplexity performs complexity validation for an input string.
// This should be called after basic input validation and hash computation.
func validateComplexity(hash string, config Config) error {
	if maxComplexity := config.effectiveMaxComplexity(); maxComplexity != -1 {
		// Create a temporary engine generator to calculate complexity
		// This is needed to access the CalculateComplexity method
		engineConfig := engine.DefaultGeneratorConfig()
		engineConfig.ColorConfig = engine.ColorConfig{
			IconPadding:         config.Padding,
			ColorSaturation:     config.ColorSaturation,
			GrayscaleSaturation: config.GrayscaleSaturation,
			ColorLightness: engine.LightnessRange{
				Min: config.ColorLightnessRange[0],
				Max: config.ColorLightnessRange[1],
			},
			GrayscaleLightness: engine.LightnessRange{
				Min: config.GrayscaleLightnessRange[0],
				Max: config.GrayscaleLightnessRange[1],
			},
			Hues:      config.HueRestrictions,
			BackColor: nil, // Not needed for complexity calculation
		}

		tempGenerator, err := engine.NewGeneratorWithConfig(engineConfig)
		if err != nil {
			return err
		}

		complexity, err := tempGenerator.CalculateComplexity(hash)
		if err != nil {
			return err
		}

		if complexity > maxComplexity {
			return NewErrComplexityLimitExceeded(maxComplexity, complexity, hash)
		}
	}
	return nil
}

// validatePNGSize performs additional validation for PNG functions that use supersampling.
// This checks the effective size (size * supersampling) against configured limits.
func validatePNGSize(size int, config Config) error {
	// Check effective size for PNG with supersampling
	effectiveSize := size * config.PNGSupersampling
	if maxSize := config.effectiveMaxIconSize(); maxSize != -1 && effectiveSize > maxSize {
		return NewErrEffectiveSizeTooLarge(maxSize, effectiveSize, size, config.PNGSupersampling)
	}

	return nil
}
