// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"strconv"
	"strings"
)

// ParseCustomerCount normalizes an exact count, not a sentence or an estimate.
// Callers must still verify that the quoted value came from the customer and
// apply the field's limits. This does not infer dates, prices, or order intent.
func ParseCustomerCount(value string) (int, bool) {
	value = strings.ToLower(strings.Join(strings.Fields(value), " "))
	if value == "" {
		return 0, false
	}
	digits := true
	for _, r := range value {
		if r < '0' || r > '9' {
			digits = false
			break
		}
	}
	if digits {
		n, err := strconv.Atoi(value)
		return n, err == nil && n > 0 && n <= 999999
	}
	units := map[string]int{"satu": 1, "dua": 2, "tiga": 3, "empat": 4, "lima": 5, "enam": 6, "tujuh": 7, "delapan": 8, "sembilan": 9, "sepuluh": 10, "sebelas": 11}
	if strings.HasPrefix(value, "ber") {
		n, ok := units[strings.TrimPrefix(value, "ber")]
		return n, ok && n >= 2 && n <= 10
	}
	var small func([]string) (int, bool)
	small = func(words []string) (int, bool) {
		if len(words) == 0 {
			return 0, true
		}
		if len(words) == 1 {
			n, ok := units[words[0]]
			return n, ok
		}
		n, ok := units[words[0]]
		if !ok || n < 1 || n > 9 {
			return 0, false
		}
		if words[1] == "belas" && n >= 2 && len(words) == 2 {
			return 10 + n, true
		}
		if words[1] == "puluh" && n >= 2 && len(words) <= 3 {
			rest, valid := small(words[2:])
			return n*10 + rest, valid && rest < 10
		}
		return 0, false
	}
	belowThousand := func(words []string) (int, bool) {
		if len(words) > 0 && words[0] == "seratus" {
			n, ok := small(words[1:])
			return 100 + n, ok
		}
		if len(words) >= 2 && words[1] == "ratus" {
			h, ok := units[words[0]]
			n, valid := small(words[2:])
			return h*100 + n, ok && h >= 2 && h <= 9 && valid
		}
		return small(words)
	}
	words := strings.Fields(value)
	if words[0] == "seribu" {
		n, ok := belowThousand(words[1:])
		return 1000 + n, ok
	}
	for i, word := range words {
		if word == "ribu" {
			h, ok := belowThousand(words[:i])
			n, valid := belowThousand(words[i+1:])
			return h*1000 + n, ok && h >= 2 && valid
		}
	}
	n, ok := belowThousand(words)
	return n, ok && n > 0
}
