package federation

import (
	"testing"
)

func TestRepoAPID(t *testing.T) {
	apid := RepoAPID("https://example.com", "alice", "myrepo")
	expected := "https://example.com/repos/alice/myrepo"
	if apid != expected {
		t.Errorf("got %q, want %q", apid, expected)
	}
}

func TestRepoAPID_TrailingSlash(t *testing.T) {
	apid := RepoAPID("https://example.com/", "bob", "app")
	expected := "https://example.com/repos/bob/app"
	if apid != expected {
		t.Errorf("got %q, want %q", apid, expected)
	}
}

func TestRepoActorJSON(t *testing.T) {
	doc := RepoActorJSON("alice", "myrepo", "A cool repo", "https://example.com")
	if doc["type"] != "Repository" {
		t.Errorf("type = %v, want Repository", doc["type"])
	}
	if doc["preferredUsername"] != "myrepo" {
		t.Errorf("preferredUsername = %v", doc["preferredUsername"])
	}
	if doc["name"] != "alice/myrepo" {
		t.Errorf("name = %v", doc["name"])
	}
	if doc["summary"] != "A cool repo" {
		t.Errorf("summary = %v", doc["summary"])
	}

	inbox, ok := doc["inbox"].(string)
	if !ok || inbox != "https://example.com/repos/alice/myrepo/inbox" {
		t.Errorf("inbox = %v", inbox)
	}
	outbox, ok := doc["outbox"].(string)
	if !ok || outbox != "https://example.com/repos/alice/myrepo/outbox" {
		t.Errorf("outbox = %v", outbox)
	}
}

func TestIsCreatePullRequest(t *testing.T) {
	tests := []struct {
		name string
		body []byte
		want bool
	}{
		{
			name: "valid Create(PullRequest)",
			body: []byte(`{"type":"Create","object":{"type":"PullRequest","summary":"fix bug"}}`),
			want: true,
		},
		{
			name: "Create with non-PR object",
			body: []byte(`{"type":"Create","object":{"type":"Note"}}`),
			want: false,
		},
		{
			name: "Follow activity",
			body: []byte(`{"type":"Follow","object":"https://example.com/users/alice"}`),
			want: false,
		},
		{
			name: "invalid JSON",
			body: []byte(`not json`),
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := IsCreatePullRequest(tt.body); got != tt.want {
				t.Errorf("IsCreatePullRequest() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestExtractInstanceURL(t *testing.T) {
	tests := []struct {
		apid string
		want string
	}{
		{"https://example.com/users/alice", "https://example.com"},
		{"http://localhost:8080/users/bob", "http://localhost:8080"},
		{"https://forge.example.org/users/charlie", "https://forge.example.org"},
	}
	for _, tt := range tests {
		t.Run(tt.apid, func(t *testing.T) {
			if got := extractInstanceURL(tt.apid); got != tt.want {
				t.Errorf("extractInstanceURL() = %q, want %q", got, tt.want)
			}
		})
	}
}
