package main

import (
	"strconv"
	"strings"
	"testing"

	"src.opensuse.org/autogits/common/gitea-generated/models"
)

func TestObsAPIHostFromWebHost(t *testing.T) {
	tests := []struct {
		name string
		api  string
		web  string
	}{
		{
			name: "api host",
			api:  "api.suse.de",
			web:  "build.suse.de",
		},
		{
			name: "api host",
			api:  "api.opensuse.org",
			web:  "build.opensuse.org",
		},
		{
			name: "other host",
			api:  "someapi.suse.de",
			web:  "someapi.suse.de",
		},
		{
			name: "short host",
			api:  "s",
			web:  "s",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if r := ObsWebHostFromApiHost(test.api); r != test.web {
				t.Error("Expected:", test.web, "but observed", r)
			}
		})
	}
}

func TestPRtoObsProjectMapping(t *testing.T) {
	tests := []struct {
		name string
		pr   string // org/repo/prNo

		expectedProject string
	}{
		{
			name:            "Regular project",
			pr:              "foobar/Repo/10",
			expectedProject: "home:foo:foobar:Repo:PR:10",
		},
		{
			name:            "underscore repo name",
			pr:              "foobar/_FooBar/10",
			expectedProject: "home:foo:foobar:XFooBar:PR:10",
		},
		{
			name:            "Underscore repo and project",
			pr:              "_some_thing/_FooBar/11",
			expectedProject: "home:foo:Xsome_thing:XFooBar:PR:11",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			s := strings.Split(test.pr, "/")
			n, _ := strconv.ParseInt(s[2], 10, 64)

			pr := models.PullRequest{
				Base: &models.PRBranchInfo{
					Repo: &models.Repository{
						Name: s[1],
						Owner: &models.User{
							UserName: s[0],
						},
					},
				},
				Index: n,
			}

			p := getObsProjectAssociatedWithPr("home:foo", &pr)
			if p != test.expectedProject {
				t.Error("invalid project:", p, "Expected:", test.expectedProject)
			}
		})
	}
}
