package forgejo

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

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

// Compile-time interface assertions.
var _ provider.WebhookAdapter = WebhookAdapter{}

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")
	}
}

func TestWebhookAdapterVerifiesSignature(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))

	tests := []struct {
		name       string
		secret     string
		signature  string
		wantErr    bool
	}{
		{
			name:       "valid signature",
			secret:     secret,
			signature:  signature,
			wantErr:    false,
		},
		{
			name:       "invalid signature",
			secret:     secret,
			signature:  "bad-signature",
			wantErr:    true,
		},
		{
			name:      "empty secret skips verification",
			secret:    "",
			signature: "",
			wantErr:   false,
		},
		{
			name:       "missing signature header with secret set",
			secret:     secret,
			signature:  "",
			wantErr:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			adapter := WebhookAdapter{Secret: tt.secret}
			req := provider.WebhookRequest{
				Provider:   provider.ProviderForgejo,
				EventType:  "push",
				Payload:    body,
				Headers: map[string][]string{"X-Forgejo-Signature": []string{tt.signature}},
				ReceivedAt: time.Now().UTC(),
			}
			err := adapter.VerifyWebhook(context.Background(), req)
			if (err != nil) != tt.wantErr {
				t.Fatalf("VerifyWebhook error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestWebhookAdapterNormalizesPushCandidate(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	body := []byte(`{
		"ref": "refs/heads/develop",
		"before": "111",
		"after": "222",
		"repository": {"name": "nomadcode", "full_name": "toki/nomadcode"},
		"commits": [{"id": "222", "modified": ["README.md"]}]
	}`)
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "push",
		ExternalID: "delivery-1",
		Payload:    body,
		Headers: map[string][]string{},
		Query:   map[string][]string{"repo_id": []string{"nomadcode"}},
		ReceivedAt: time.Date(2026, 6, 19, 10, 0, 0, 0, time.UTC),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err != nil {
		t.Fatalf("NormalizeWebhook error: %v", err)
	}
	if len(candidates) != 1 {
		t.Fatalf("expected 1 candidate, got %d", len(candidates))
	}
	c := candidates[0]
	if c.Type != "branch.updated" {
		t.Fatalf("candidate type: got %q", c.Type)
	}
	if c.Provider != provider.ProviderForgejo {
		t.Fatalf("candidate provider: got %q", c.Provider)
	}
	if c.ExternalID != "delivery-1" {
		t.Fatalf("candidate externalID: got %q", c.ExternalID)
	}
	if c.Revision == nil {
		t.Fatal("candidate revision is nil")
	}
	if c.Revision.RepoID != "nomadcode" || c.Revision.Branch != "develop" {
		t.Fatalf("unexpected revision: %+v", c.Revision)
	}
}

func TestWebhookAdapterIgnoresUnsupportedEvent(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "repository",
		Payload:    []byte(`{"action": "created"}`),
		Headers: map[string][]string{},
		ReceivedAt: time.Now().UTC(),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err != nil {
		t.Fatalf("NormalizeWebhook error: %v", err)
	}
	if len(candidates) != 0 {
		t.Fatalf("expected 0 candidates for unsupported event, got %d", len(candidates))
	}
}

func TestWebhookAdapterTreatsEmptyEventAsPush(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	body := []byte(`{
		"ref": "refs/heads/develop",
		"before": "111",
		"after": "222",
		"repository": {"name": "nomadcode", "full_name": "toki/nomadcode"},
		"commits": [{"id": "222", "modified": ["README.md"]}]
	}`)
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "",
		ExternalID: "delivery-1",
		Payload:    body,
		Headers:    map[string][]string{},
		Query:      map[string][]string{"repo_id": []string{"nomadcode"}},
		ReceivedAt: time.Date(2026, 6, 19, 10, 0, 0, 0, time.UTC),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err != nil {
		t.Fatalf("NormalizeWebhook error: %v", err)
	}
	if len(candidates) != 1 {
		t.Fatalf("expected 1 candidate for empty event type, got %d", len(candidates))
	}
	if candidates[0].Revision == nil {
		t.Fatal("candidate revision is nil")
	}
	if candidates[0].Revision.Branch != "develop" {
		t.Fatalf("branch: got %q", candidates[0].Revision.Branch)
	}
}

func TestWebhookAdapterRejectsMalformedPayload(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "push",
		ExternalID: "delivery-1",
		Payload:    []byte(`{malformed json`),
		Headers:    map[string][]string{},
		Query:      map[string][]string{},
		ReceivedAt: time.Date(2026, 6, 19, 10, 0, 0, 0, time.UTC),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err == nil {
		t.Fatalf("expected error for malformed payload, got nil")
	}
	if candidates != nil {
		t.Fatalf("expected nil candidates on error, got %#v", candidates)
	}
}

func TestWebhookAdapterFallsBackToRepositoryName(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	body := []byte(`{
		"ref": "refs/heads/develop",
		"before": "111",
		"after": "222",
		"repository": {"name": "nomadcode"},
		"commits": [{"id": "222", "modified": ["README.md"]}]
	}`)
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "push",
		ExternalID: "delivery-1",
		Payload:    body,
		Headers:    map[string][]string{},
		Query:      map[string][]string{},
		ReceivedAt: time.Date(2026, 6, 19, 10, 0, 0, 0, time.UTC),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err != nil {
		t.Fatalf("NormalizeWebhook error: %v", err)
	}
	if len(candidates) != 1 {
		t.Fatalf("expected 1 candidate, got %d", len(candidates))
	}
	if candidates[0].Revision.RepoID != "nomadcode" {
		t.Fatalf("repo_id: got %q, want %q", candidates[0].Revision.RepoID, "nomadcode")
	}
}

func TestWebhookAdapterErrorWhenNoRepoIDSource(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	body := []byte(`{
		"ref": "refs/heads/develop",
		"before": "111",
		"after": "222",
		"repository": {},
		"commits": [{"id": "222"}]
	}`)
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "push",
		ExternalID: "delivery-1",
		Payload:    body,
		Headers:    map[string][]string{},
		Query:      map[string][]string{},
		ReceivedAt: time.Date(2026, 6, 19, 10, 0, 0, 0, time.UTC),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err == nil {
		t.Fatalf("expected error when no repo_id source available, got nil")
	}
	if candidates != nil {
		t.Fatalf("expected nil candidates on error, got %#v", candidates)
	}
	if err != ErrInvalidPushPayload {
		t.Fatalf("error: got %v, want %v", err, ErrInvalidPushPayload)
	}
}

func TestWebhookAdapterIgnoresTagRef(t *testing.T) {
	adapter := WebhookAdapter{Secret: "secret"}
	body := []byte(`{
		"ref": "refs/tags/v1",
		"before": "111",
		"after": "222",
		"repository": {"name": "nomadcode", "full_name": "toki/nomadcode"}
	}`)
	req := provider.WebhookRequest{
		Provider:   provider.ProviderForgejo,
		EventType:  "push",
		Payload:    body,
		Headers: map[string][]string{},
		ReceivedAt: time.Now().UTC(),
	}

	candidates, err := adapter.NormalizeWebhook(context.Background(), req)
	if err != nil {
		t.Fatalf("NormalizeWebhook error: %v", err)
	}
	if len(candidates) != 0 {
		t.Fatalf("expected 0 candidates for tag ref, got %d", len(candidates))
	}
}
