package services

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

// SendWhatsAppMessage sends a text reply using the specific Client's credentials
func SendWhatsAppMessage(token, phoneID, toPhone, messageBody string) error {
	version := "v17.0"
	url := fmt.Sprintf("https://graph.facebook.com/%s/%s/messages", version, phoneID)

	payload := map[string]interface{}{
		"messaging_product": "whatsapp",
		"to":                toPhone,
		"type":              "text",
		"text": map[string]string{
			"body": messageBody,
		},
	}

	jsonData, _ := json.Marshal(payload)
	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		return fmt.Errorf("whatsapp api error: status %d", resp.StatusCode)
	}

	return nil
}
