package utils

import (
	"sort"
	"strconv"
	"strings"
)

// NormalizeTrim returns the input string without leading/trailing whitespace.
func NormalizeTrim(value string) string {
	return strings.TrimSpace(value)
}

// NormalizeUpper returns the trimmed, upper-case version of value.
func NormalizeUpper(value string) string {
	return strings.ToUpper(NormalizeTrim(value))
}

// NormalizeFlag trims whitespace, removes surrounding brackets/quotes and returns upper-case flag
func NormalizeFlag(value string) string {
	v := NormalizeTrim(value)
	v = strings.Trim(v, "[]\"'")
	return strings.ToUpper(v)
}

// ParseFlags parses a raw flags string like "[DOC, PAKAN]" or "DOC,PAKAN"
// and returns a deduplicated, sorted slice of normalized flags (upper-case, trimmed).
func ParseFlags(raw string) []string {
	if raw == "" {
		return nil
	}
	parts := strings.Split(raw, ",")
	set := make(map[string]struct{}, len(parts))
	for _, p := range parts {
		f := NormalizeFlag(p)
		if f == "" {
			continue
		}
		set[f] = struct{}{}
	}
	if len(set) == 0 {
		return nil
	}
	res := make([]string, 0, len(set))
	for k := range set {
		res = append(res, k)
	}
	sort.Strings(res)
	return res
}

// ParseQueryArray parses comma-separated string values and returns a slice of trimmed strings
// Example: "a, b, c" → ["a", "b", "c"]
func ParseQueryArray(raw string) []string {
	if raw == "" {
		return nil
	}

	parts := strings.Split(raw, ",")
	result := make([]string, 0, len(parts))

	for _, p := range parts {
		trimmed := strings.TrimSpace(p)
		if trimmed != "" {
			result = append(result, trimmed)
		}
	}

	if len(result) == 0 {
		return nil
	}
	return result
}

// ParseQueryUintArray parses comma-separated string values and returns a slice of uint
// Invalid values are skipped
// Example: "1, 2, 3" → [1, 2, 3]
func ParseQueryUintArray(raw string) []uint {
	if raw == "" {
		return nil
	}

	parts := strings.Split(raw, ",")
	result := make([]uint, 0, len(parts))

	for _, p := range parts {
		trimmed := strings.TrimSpace(p)
		if trimmed == "" {
			continue
		}

		if num, err := strconv.ParseUint(trimmed, 10, 32); err == nil {
			result = append(result, uint(num))
		}
	}

	if len(result) == 0 {
		return nil
	}
	return result
}
