package utils

import (
	"fmt"
	"strings"
)

// FormatPhoneToJID converts a phone number to WhatsApp JID format
// If the number already contains @, it returns as-is
// Otherwise, applies formatting rules:
// - If starts with 0, assumes no country code and replaces 0 with country code
// - If starts with +, assumes it already has country code
// - Otherwise adds country code if not present
// - Adds @s.whatsapp.net suffix
func FormatPhoneToJID(phone string, defaultCountryCode string) string {
	// If already in JID format, return as-is
	if strings.Contains(phone, "@") {
		return phone
	}

	// Remove all non-digit characters
	cleaned := strings.Map(func(r rune) rune {
		if r >= '0' && r <= '9' {
			return r
		}
		return -1
	}, phone)

	// If empty after cleaning, return original
	if cleaned == "" {
		return phone
	}

	// If number starts with 0, it definitely doesn't have a country code
	// Replace the leading 0 with the country code
	if strings.HasPrefix(cleaned, "0") && defaultCountryCode != "" {
		countryCode := strings.TrimPrefix(defaultCountryCode, "+")
		cleaned = countryCode + strings.TrimLeft(cleaned, "0")
		return fmt.Sprintf("%s@s.whatsapp.net", cleaned)
	}

	// Remove all leading zeros
	cleaned = strings.TrimLeft(cleaned, "0")

	// If original phone started with +, it already has country code
	if strings.HasPrefix(phone, "+") {
		return fmt.Sprintf("%s@s.whatsapp.net", cleaned)
	}

	// Add country code if provided and number doesn't start with it
	if defaultCountryCode != "" {
		countryCode := strings.TrimPrefix(defaultCountryCode, "+")
		if !strings.HasPrefix(cleaned, countryCode) {
			cleaned = countryCode + cleaned
		}
	}

	return fmt.Sprintf("%s@s.whatsapp.net", cleaned)
}

// IsGroupJID checks if a JID is a group JID
func IsGroupJID(jid string) bool {
	return strings.HasSuffix(jid, "@g.us")
}

// IsValidJID checks if a string is a valid WhatsApp JID
func IsValidJID(jid string) bool {
	return strings.Contains(jid, "@") &&
		(strings.HasSuffix(jid, "@s.whatsapp.net") ||
			strings.HasSuffix(jid, "@g.us") ||
			strings.HasSuffix(jid, "@broadcast"))
}
