package notification

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

type Service struct {
	apiURL   string
	apiKey   string
	instance string
}

func NewService() *Service {
	// Hardcoded configuration as per user request
	return &Service{
		apiURL:   "https://others-evolution-api.nsowe9.easypanel.host",
		apiKey:   "429683C4C977415CAAFCCE10F7D57E11",
		instance: "NANDO",
	}
}

type MessageRequest struct {
	Number string `json:"number"`
	Text   string `json:"text"`
}

func (s *Service) SendWhatsApp(number string, message string) error {
	cleanNumber := cleanPhoneNumber(number)
	if cleanNumber == "" {
		return fmt.Errorf("número de telefone inválido ou vazio")
	}

	url := fmt.Sprintf("%s/message/sendText/%s", s.apiURL, s.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
}
