// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

// Package phone keeps phone identities consistent across storage and WhatsApp.
// It does not guess a foreign national numbering plan or check WA registration.
package phone

import (
	"strings"
	"unicode"
)

// Normalize returns country-code digits. + and 00 explicitly mark international
// input. A single leading 0 keeps the existing Indonesian national convention.
// Bare digits already contain the country code: in particular, 81/82/84/86/88
// must never gain a 62 prefix. Normalization is idempotent.
func Normalize(raw string) string {
	raw = strings.TrimSpace(raw)
	if user, server, found := strings.Cut(raw, "@"); found {
		// Only phone JIDs represent phone numbers. LIDs must be resolved via WA,
		// and group JIDs must retain their own identity outside this helper.
		if server != "s.whatsapp.net" && server != "c.us" {
			return ""
		}
		if account, device, found := strings.Cut(user, ":"); found {
			if !digitsOnly(device) {
				return ""
			}
			user = account
		}
		if !digitsOnly(user) || user[0] == '0' {
			return ""
		}
		return user
	}
	explicit := strings.HasPrefix(raw, "+")
	raw = strings.TrimPrefix(raw, "+")
	var b strings.Builder
	for _, r := range raw {
		switch {
		case r >= '0' && r <= '9':
			b.WriteRune(r)
		case unicode.IsSpace(r) || r == '-' || r == '.' || r == '(' || r == ')':
			// Display separators only: never extract digits from arbitrary text.
		default:
			return ""
		}
	}
	d := b.String()
	if !explicit && strings.HasPrefix(d, "00") {
		d, explicit = d[2:], true
	}
	if d == "" {
		return ""
	}
	if explicit {
		if d[0] == '0' {
			return ""
		}
		return d
	}
	if d[0] == '0' {
		return "62" + d[1:]
	}
	return d
}

func digitsOnly(value string) bool {
	if value == "" {
		return false
	}
	for _, r := range value {
		if r < '0' || r > '9' {
			return false
		}
	}
	return true
}

// Validate checks canonical syntax, not whether a number is allocated or on WA.
// Seven digits permits short national plans; E.164 caps the total at 15 digits.
func Validate(number string) (bool, string) {
	if number == "" {
		return false, "nomor kosong atau format tidak valid"
	}
	if !digitsOnly(number) || number[0] == '0' {
		return false, "gunakan digit dengan kode negara, diawali 1–9"
	}
	if len(number) < 7 || len(number) > 15 {
		return false, "nomor dengan kode negara harus 7–15 digit"
	}
	return true, ""
}
