package notify

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

	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/models"
)

var httpClient = &http.Client{Timeout: 10 * time.Second}

func postJSON(target string, payload any) error {
	body, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	resp, err := httpClient.Post(target, "application/json", bytes.NewReader(body))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d from %s", resp.StatusCode, target)
	}
	return nil
}

func dispatchWebhook(ch models.NotificationChannel, ev Event) error {
	target := ch.Config["url"]
	if target == "" {
		return fmt.Errorf("webhook: missing url")
	}
	return postJSON(target, map[string]any{
		"monitor":    ev.MonitorName,
		"type":       ev.Type,
		"old_status": ev.OldStatus,
		"new_status": ev.NewStatus,
		"message":    ev.Message,
		"time":       ev.Time.Format(time.RFC3339),
	})
}

func dispatchDiscord(ch models.NotificationChannel, ev Event) error {
	target := ch.Config["url"]
	if target == "" {
		return fmt.Errorf("discord: missing url")
	}
	return postJSON(target, map[string]string{"content": ev.title()})
}

func dispatchSlack(ch models.NotificationChannel, ev Event) error {
	target := ch.Config["url"]
	if target == "" {
		return fmt.Errorf("slack: missing url")
	}
	return postJSON(target, map[string]string{"text": ev.title()})
}

func dispatchTelegram(ch models.NotificationChannel, ev Event) error {
	token := ch.Config["token"]
	chatID := ch.Config["chat_id"]
	if token == "" || chatID == "" {
		return fmt.Errorf("telegram: missing token or chat_id")
	}
	api := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
	return postJSON(api, map[string]string{"chat_id": chatID, "text": ev.title()})
}
