// Copyright 2026 Moko Consulting <hello@mokoconsulting.tech>
// SPDX-License-Identifier: GPL-3.0-or-later

package ntfy

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/log"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/setting"
)

// Send publishes a notification to the ntfy server.
func Send(topic, title, message, priority, tags string) error {
	if !setting.Ntfy.Enabled || setting.Ntfy.ServerURL == "" {
		return nil
	}

	if topic == "" {
		topic = setting.Ntfy.DefaultTopic
	}

	url := fmt.Sprintf("%s/%s", strings.TrimRight(setting.Ntfy.ServerURL, "/"), topic)

	req, err := http.NewRequest("POST", url, strings.NewReader(message))
	if err != nil {
		return fmt.Errorf("ntfy request: %w", err)
	}

	req.Header.Set("Title", title)
	if priority != "" {
		req.Header.Set("Priority", priority)
	}
	if tags != "" {
		req.Header.Set("Tags", tags)
	}
	if setting.Ntfy.Token != "" {
		req.Header.Set("Authorization", "Bearer "+setting.Ntfy.Token)
	}

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("ntfy send: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		return fmt.Errorf("ntfy returned status %d", resp.StatusCode)
	}

	log.Debug("ntfy notification sent: %s — %s", topic, title)
	return nil
}

// SendAsync sends a notification in a goroutine (non-blocking).
func SendAsync(topic, title, message, priority, tags string) {
	go func() {
		if err := Send(topic, title, message, priority, tags); err != nil {
			log.Error("ntfy async send failed: %v", err)
		}
	}()
}
