package notification

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestWebhookSendsCorrectPayloadAndHeaders(t *testing.T) {
	t.Parallel()
	var got webhookBody
	var auth, custom string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		auth = r.Header.Get("Authorization")
		custom = r.Header.Get("X-Test")
		_ = json.NewDecoder(r.Body).Decode(&got)
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	ch := NewWebhookChannel(WebhookConfig{
		URL: srv.URL, BearerToken: "tok-123",
		HeaderName: "X-Test", HeaderValue: "yes",
	})
	code, _, err := ch.Send(context.Background(), Payload{
		Event: EventRaised, AlertID: "01K",
		Severity: "warning", Kind: "backup_failed",
		HostID: "h1", HostName: "alfa-01",
		Message:  "Backup failed",
		RaisedAt: time.Date(2026, 5, 4, 15, 42, 1, 0, time.UTC),
		Link:     "https://rm.example/alerts/01K",
	})
	if err != nil {
		t.Fatalf("send: %v", err)
	}
	if code != 200 {
		t.Errorf("status: %d", code)
	}
	if got.Event != "alert.raised" || got.Kind != "backup_failed" || got.Message != "Backup failed" {
		t.Errorf("body: %+v", got)
	}
	if auth != "Bearer tok-123" {
		t.Errorf("auth: %q", auth)
	}
	if custom != "yes" {
		t.Errorf("custom header: %q", custom)
	}
}

func TestWebhookReturnsErrorOn4xx(t *testing.T) {
	t.Parallel()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusUnauthorized)
	}))
	defer srv.Close()
	ch := NewWebhookChannel(WebhookConfig{URL: srv.URL})
	code, _, err := ch.Send(context.Background(), Payload{Event: EventRaised})
	if err == nil {
		t.Fatal("expected error for 401")
	}
	if code != 401 {
		t.Errorf("code: %d", code)
	}
}

func TestWebhookRespectsCtxTimeout(t *testing.T) {
	t.Parallel()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		time.Sleep(2 * time.Second)
		w.WriteHeader(200)
	}))
	defer srv.Close()
	ch := NewWebhookChannel(WebhookConfig{URL: srv.URL})
	ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()
	_, _, err := ch.Send(ctx, Payload{Event: EventRaised})
	if err == nil {
		t.Fatal("expected timeout error")
	}
}
