package forgejo

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"reflect"
	"testing"
	"time"

	"git.toki-labs.com/toki/gito/services/core/internal/core"
)

func TestNormalizePushPayload(t *testing.T) {
	payload, err := ParsePushPayload([]byte(`{
		"ref": "refs/heads/develop",
		"before": "111",
		"after": "222",
		"repository": {
			"name": "nomadcode",
			"full_name": "toki/nomadcode",
			"default_branch": "develop"
		},
		"commits": [
			{"id": "222", "added": ["agent-roadmap/new.md"], "modified": ["README.md"], "removed": ["old.md"]}
		]
	}`))
	if err != nil {
		t.Fatalf("ParsePushPayload: %v", err)
	}

	observedAt := time.Date(2026, 6, 13, 10, 0, 0, 0, time.UTC)
	event, err := NormalizePush(payload, "", observedAt)
	if err != nil {
		t.Fatalf("NormalizePush: %v", err)
	}

	if event.RepoID != "toki/nomadcode" || event.Branch != "develop" {
		t.Fatalf("unexpected event identity: %+v", event)
	}
	if event.Before != "111" || event.After != "222" {
		t.Fatalf("unexpected revisions: %+v", event)
	}
	if !event.ObservedAt.Equal(observedAt) {
		t.Fatalf("observed_at: got %s", event.ObservedAt)
	}
	want := []core.ChangedFile{
		{Path: "README.md", ChangeType: "modified"},
		{Path: "agent-roadmap/new.md", ChangeType: "added"},
		{Path: "old.md", ChangeType: "deleted"},
	}
	if !reflect.DeepEqual(event.ChangedFiles, want) {
		t.Fatalf("changed files:\n got %#v\nwant %#v", event.ChangedFiles, want)
	}
}

func TestNormalizePushAllowsRepoIDOverride(t *testing.T) {
	payload := PushPayload{
		Ref:    "refs/heads/main",
		Before: "111",
		After:  "222",
		Repository: Repository{
			FullName: "toki/nomadcode",
		},
	}
	event, err := NormalizePush(payload, "nomadcode", time.Time{})
	if err != nil {
		t.Fatalf("NormalizePush: %v", err)
	}
	if event.RepoID != "nomadcode" {
		t.Fatalf("RepoID: got %q", event.RepoID)
	}
}

func TestNormalizePushRejectsTags(t *testing.T) {
	payload := PushPayload{
		Ref:    "refs/tags/v1",
		Before: "111",
		After:  "222",
		Repository: Repository{
			FullName: "toki/nomadcode",
		},
	}
	if _, err := NormalizePush(payload, "", time.Time{}); err == nil {
		t.Fatal("expected tag ref to be rejected")
	}
}

func TestVerifySignature(t *testing.T) {
	body := []byte(`{"ref":"refs/heads/develop"}`)
	secret := "forgejo-secret"
	mac := hmac.New(sha256.New, []byte(secret))
	_, _ = mac.Write(body)
	signature := hex.EncodeToString(mac.Sum(nil))

	if !VerifySignature(secret, body, signature) {
		t.Fatal("expected plain hex signature to verify")
	}
	if !VerifySignature(secret, body, "sha256="+signature) {
		t.Fatal("expected prefixed signature to verify")
	}
	if VerifySignature(secret, body, "bad-signature") {
		t.Fatal("bad signature verified")
	}
}
