package cybersecurity

import (
	"regexp"
	"strings"
)

var sqliPatterns = []struct {
	name string
	re   *regexp.Regexp
}{
	{"union_select", regexp.MustCompile(`(?i)\bunion\s+(all\s+)?select\b`)},
	{"or_1_eq_1", regexp.MustCompile(`(?i)\bor\s+1\s*=\s*1`)},
	{"comment_injection", regexp.MustCompile(`(--|#|/\*)\s*$`)},
	{"single_quote_or", regexp.MustCompile(`(?i)'\s*(or|and)\s+'`)},
	{"drop_table", regexp.MustCompile(`(?i)\bdrop\s+(table|database)\b`)},
	{"sleep_benchmark", regexp.MustCompile(`(?i)\b(sleep|benchmark)\s*\(`)},
	{"exec_xp", regexp.MustCompile(`(?i)\b(exec|xp_)\w*`)},
	{"tautology", regexp.MustCompile(`(?i)\bor\s+['"]?\w+['"]?\s*=\s*['"]?\w+['"]?`)},
	{"stacked_query", regexp.MustCompile(`;\s*(select|insert|update|delete|drop|alter)\b`)},
}

// DetectSQLInjection analiza un input en busca de patrones heuristicos de inyeccion SQL.
// Devuelve si se detecto una amenaza y el nombre del patron encontrado.
func DetectSQLInjection(input string) (isThreat bool, pattern string) {
	normalized := strings.TrimSpace(input)
	for _, p := range sqliPatterns {
		if p.re.MatchString(normalized) {
			return true, p.name
		}
	}
	return false, ""
}
