package notification import ( "bytes" "encoding/json" "fmt" "log" "net/http" "regexp" ) type Service struct { apiURL string apiKey string instanceSP string instanceMG string } func NewService(apiURL, apiKey, instanceSP, instanceMG string) *Service { return &Service{ apiURL: apiURL, apiKey: apiKey, instanceSP: instanceSP, instanceMG: instanceMG, } } type MessageRequest struct { Number string `json:"number"` Text string `json:"text"` } func (s *Service) SendWhatsApp(number string, message string, regiao string) error { cleanNumber := cleanPhoneNumber(number) if cleanNumber == "" { return fmt.Errorf("número de telefone inválido ou vazio") } instance := s.instanceSP // default if regiao == "MG" { instance = s.instanceMG } url := fmt.Sprintf("%s/message/sendText/%s", s.apiURL, instance) payload := MessageRequest{ Number: cleanNumber, Text: message, } jsonData, err := json.Marshal(payload) if err != nil { return fmt.Errorf("erro ao criar payload JSON: %v", err) } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { return fmt.Errorf("erro ao criar requisição HTTP: %v", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("apikey", s.apiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil { return fmt.Errorf("erro ao enviar requisição para Evolution API: %v", err) } defer resp.Body.Close() if resp.StatusCode >= 400 { return fmt.Errorf("erro na API da Evolution: Status Code %d", resp.StatusCode) } log.Printf("WhatsApp enviado para %s com sucesso.", cleanNumber) return nil } func cleanPhoneNumber(phone string) string { // Remove all non-numeric characters re := regexp.MustCompile(`\D`) clean := re.ReplaceAllString(phone, "") // Basic validation length (BR numbers usually 10 or 11 digits without DDI) // If it doesn't have DDI (10 or 11 chars), add 55 if len(clean) >= 10 && len(clean) <= 11 { return "55" + clean } return clean }