package notify

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

func TestLark_HappyPath_WithSigning(t *testing.T) {
	fixedTS := int64(1712923200)
	secret := "sec-123"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			t.Errorf("method=%s", r.Method)
		}
		if r.Header.Get("Content-Type") != "application/json" {
			t.Errorf("ct=%s", r.Header.Get("Content-Type"))
		}
		var msg larkTextMsg
		if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
			t.Fatal(err)
		}
		if msg.MsgType != "text" {
			t.Errorf("msg_type=%s", msg.MsgType)
		}
		if msg.Content.Text != "hello world" {
			t.Errorf("text=%s", msg.Content.Text)
		}
		if msg.Timestamp != "1712923200" {
			t.Errorf("timestamp=%s", msg.Timestamp)
		}
		// Recompute the expected sign for the fixed timestamp + secret
		want, err := genSign(secret, fixedTS)
		if err != nil {
			t.Fatal(err)
		}
		if msg.Sign != want {
			t.Errorf("sign mismatch: got %s want %s", msg.Sign, want)
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	c := NewLarkClient(srv.URL, secret, 5*time.Second)
	c.now = func() time.Time { return time.Unix(fixedTS, 0) }
	if err := c.SendText(context.Background(), "hello world"); err != nil {
		t.Fatal(err)
	}
}

func TestLark_WithoutSigning_OmitsFields(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var raw map[string]any
		_ = json.NewDecoder(r.Body).Decode(&raw)
		if _, has := raw["timestamp"]; has {
			t.Error("unsigned send should omit timestamp")
		}
		if _, has := raw["sign"]; has {
			t.Error("unsigned send should omit sign")
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()
	c := NewLarkClient(srv.URL, "", 5*time.Second)
	if err := c.SendText(context.Background(), "no-sign"); err != nil {
		t.Fatal(err)
	}
}

func TestLark_RetriesOn5xx(t *testing.T) {
	var calls int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		n := atomic.AddInt32(&calls, 1)
		if n < 3 {
			http.Error(w, "down", http.StatusBadGateway)
			return
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()
	c := NewLarkClient(srv.URL, "", 5*time.Second)
	if err := c.SendText(context.Background(), "x"); err != nil {
		t.Fatal(err)
	}
	if atomic.LoadInt32(&calls) != 3 {
		t.Errorf("want 3 calls, got %d", calls)
	}
}

func TestLark_FailsAfterExhausting(t *testing.T) {
	var calls int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(&calls, 1)
		http.Error(w, "down", http.StatusServiceUnavailable)
	}))
	defer srv.Close()
	c := NewLarkClient(srv.URL, "", 5*time.Second)
	err := c.SendText(context.Background(), "x")
	if err == nil {
		t.Error("expected error after all retries fail")
	}
	if atomic.LoadInt32(&calls) != 3 {
		t.Errorf("want 3 calls, got %d", calls)
	}
	if !strings.Contains(err.Error(), "503") {
		t.Errorf("error should mention status: %v", err)
	}
}

func TestGenSign_Determinism(t *testing.T) {
	// Same inputs -> same output
	a, _ := genSign("secret", 1000)
	b, _ := genSign("secret", 1000)
	if a != b {
		t.Error("not deterministic")
	}
	// Different timestamp -> different output
	c, _ := genSign("secret", 1001)
	if a == c {
		t.Error("ts should affect sign")
	}
	// Different secret -> different output
	d, _ := genSign("other", 1000)
	if a == d {
		t.Error("secret should affect sign")
	}
}
