// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"
)

// Foreign numbers in prose require +/00 to avoid turning prices/order IDs into
// links. Existing Indonesian 08/628 notation remains supported.
var waNumberRe = regexp.MustCompile(`(?:\+[1-9]|00[1-9]|628|08)[0-9 ().\-]*[0-9]`)

func phoneMatchesInText(text string) [][]int {
	var matches [][]int
	for _, loc := range waNumberRe.FindAllStringIndex(text, -1) {
		if loc[0] > 0 {
			before, _ := utf8.DecodeLastRuneInString(text[:loc[0]])
			if unicode.IsLetter(before) || unicode.IsDigit(before) || strings.ContainsRune("/_+@", before) {
				continue
			}
		}
		if loc[1] < len(text) {
			after, _ := utf8.DecodeRuneInString(text[loc[1]:])
			if unicode.IsLetter(after) || unicode.IsDigit(after) || after == '@' {
				continue
			}
		}
		if normalizeWANumber(text[loc[0]:loc[1]]) != "" {
			matches = append(matches, loc)
		}
	}
	return matches
}

// LinkifyWhatsApp mengubah nomor WhatsApp pada teks jadi tautan https://wa.me/<intl> yang bisa diklik.
// Nomor milik bot sendiri (ownNumber) dilewati—pelanggan toh sudah terhubung di chat ini.
func LinkifyWhatsApp(text, ownNumber string) string {
	own := normalizeWANumber(ownNumber)
	locs := phoneMatchesInText(text)
	if len(locs) == 0 {
		return text
	}
	var b strings.Builder
	last := 0
	for _, loc := range locs {
		start, end := loc[0], loc[1]
		intl := normalizeWANumber(text[start:end])
		if intl == "" || (own != "" && intl == own) {
			continue // bukan nomor valid atau nomor sendiri -> biarkan apa adanya
		}
		b.WriteString(text[last:start])
		b.WriteString("https://wa.me/" + intl)
		last = end
	}
	b.WriteString(text[last:])
	return b.String()
}

// normalizeWANumber follows the same contract as Inbox and contact imports.
func normalizeWANumber(s string) string {
	d := NormalizePhone(s)
	if valid, _ := ValidatePhoneForWA(d); !valid {
		return ""
	}
	return d
}
