package mailstore

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

// CheckRspamd sends a message to an optional rspamd instance for scoring, only called
// when [Rspamd] enabled=true — the built-in SpamScore heuristic (spam.go) always runs
// regardless, so this is additive, not a replacement.
func CheckRspamd(url string, raw []byte, mailFrom, rcptTo string) (score float64, action string, err error) {
	req, err := http.NewRequest(http.MethodPost, url+"/checkv2", bytes.NewReader(raw))
	if err != nil {
		return 0, "", err
	}
	req.Header.Set("From", mailFrom)
	req.Header.Set("Rcpt", rcptTo)
	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	var result struct {
		Score  float64 `json:"score"`
		Action string  `json:"action"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return 0, "", err
	}
	return result.Score, result.Action, nil
}
