package webhooks

import (
	"net/http/httptest"
	"testing"
)

func TestValidateHMAC(t *testing.T) {
	secret := []byte("hunter2-secret-token")
	body := []byte(`{"hello":"world"}`)
	expected := computeHex(secret, body)

	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("X-Hub-Signature-256", "sha256="+expected)
	ok, why := Validate(r, body, secret)
	if !ok {
		t.Errorf("expected valid, got: %s", why)
	}
}

func TestValidateHMACTamperedBody(t *testing.T) {
	secret := []byte("s")
	body := []byte(`{"hello":"world"}`)
	expected := computeHex(secret, body)

	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("X-Webhook-Signature-256", "sha256="+expected)
	ok, _ := Validate(r, []byte(`{"hello":"tampered"}`), secret)
	if ok {
		t.Error("expected validation to fail on tampered body")
	}
}

func TestValidateToken(t *testing.T) {
	secret := []byte("plain-token-abcdef")
	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("X-Webhook-Token", string(secret))
	ok, _ := Validate(r, []byte("anything"), secret)
	if !ok {
		t.Error("expected token validation to pass")
	}
}

func TestValidateBearer(t *testing.T) {
	secret := []byte("bearer-token-xyz")
	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("Authorization", "Bearer "+string(secret))
	ok, _ := Validate(r, nil, secret)
	if !ok {
		t.Error("expected Bearer validation to pass")
	}
}

func TestValidateNoSecret(t *testing.T) {
	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("X-Webhook-Token", "anything")
	ok, _ := Validate(r, nil, nil)
	if ok {
		t.Error("expected validation to fail with empty secret")
	}
}

func TestValidateNoHeaders(t *testing.T) {
	r := httptest.NewRequest("POST", "/", nil)
	ok, _ := Validate(r, []byte("x"), []byte("y"))
	if ok {
		t.Error("expected validation to fail with no headers present")
	}
}

func TestValidateBadHMACFormat(t *testing.T) {
	r := httptest.NewRequest("POST", "/", nil)
	r.Header.Set("X-Hub-Signature-256", "not-hex-and-no-prefix")
	ok, _ := Validate(r, []byte("x"), []byte("y"))
	if ok {
		t.Error("expected validation to fail on malformed signature")
	}
}
