package message

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

// Discord webhook payload
type discordPayload struct {
	Content string `json:"content"`
}

func SendDiscordNotification(filename string, message string) error {
	webhookURL := os.Getenv("DISCORD_WEBHOOK_URL")
	if webhookURL == "" {
		log.Printf("DISCORD_WEBHOOK_URL environment variable not set")
		return fmt.Errorf("DISCORD_WEBHOOK_URL environment variable not set")
	}

	todays_date := time.Now().Format("02/01/2006")
	title := "# " + todays_date + " - Resumo semanal - *" + filename + "*"

	content := title + "\n" + message
	runes := []rune(content)
	maxLen := 1800

	for i := 0; i < len(runes); {
		end := i + maxLen
		if end >= len(runes) {
			end = len(runes)
		} else {
			for end < len(runes) && runes[end] != '\n' {
				end++
			}
			if end < len(runes) && runes[end] == '\n' {
				end++
			}
		}
		chunk := string(runes[i:end])
		payload := discordPayload{Content: chunk}

		jsonData, err := json.Marshal(payload)
		if err != nil {
			log.Printf("Failed to marshal Discord payload: %v", err)
			return err
		}

		log.Printf("Sending Discord notification chunk (start: %d, end: %d)", i, end)
		resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			log.Printf("Error posting to Discord webhook: %v", err)
			return err
		}

		if resp.StatusCode < 200 || resp.StatusCode >= 300 {
			log.Printf("Discord webhook returned status: %s", resp.Status)
			resp.Body.Close()
			return fmt.Errorf("Discord webhook returned status: %s", resp.Status)
		}
		resp.Body.Close()

		i = end
	}

	log.Printf("Discord notification sent successfully: Title='%s'", title)
	return nil
}
