package vcs

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestParseRepoRef_HTTPS(t *testing.T) {
	cases := []struct{ url, owner, name string }{
		{"https://git.jerryyan.net/owner/repo.git", "owner", "repo"},
		{"https://git.jerryyan.net/owner/repo", "owner", "repo"},
		{"http://git.jerryyan.net/acme/widgets.git", "acme", "widgets"},
		{"https://git.jerryyan.net:3000/owner/repo.git", "owner", "repo"},
	}
	for _, c := range cases {
		ref, err := ParseRepoRef(c.url, "git.jerryyan.net")
		require.NoError(t, err, c.url)
		assert.Equal(t, c.owner, ref.Owner, c.url)
		assert.Equal(t, c.name, ref.Name, c.url)
	}
}

func TestParseRepoRef_SSHAndScp(t *testing.T) {
	cases := []struct{ url, owner, name string }{
		{"git@git.jerryyan.net:owner/repo.git", "owner", "repo"},
		{"git@git.jerryyan.net:owner/repo", "owner", "repo"},
		{"ssh://git@git.jerryyan.net/owner/repo.git", "owner", "repo"},
	}
	for _, c := range cases {
		ref, err := ParseRepoRef(c.url, "git.jerryyan.net")
		require.NoError(t, err, c.url)
		assert.Equal(t, c.owner, ref.Owner, c.url)
		assert.Equal(t, c.name, ref.Name, c.url)
	}
}

func TestParseRepoRef_UnsupportedHost(t *testing.T) {
	_, err := ParseRepoRef("https://github.com/owner/repo.git", "git.jerryyan.net")
	require.ErrorIs(t, err, ErrUnsupportedHost)

	_, err = ParseRepoRef("git@github.com:owner/repo.git", "git.jerryyan.net")
	require.ErrorIs(t, err, ErrUnsupportedHost)
}

func TestParseRepoRef_Invalid(t *testing.T) {
	for _, bad := range []string{"", "not-a-url", "https://git.jerryyan.net/only-owner"} {
		_, err := ParseRepoRef(bad, "git.jerryyan.net")
		require.Error(t, err, bad)
	}
}

func TestParseRepoRef_HostAgnostic(t *testing.T) {
	// wantHost empty => skip host check
	ref, err := ParseRepoRef("https://github.com/owner/repo.git", "")
	require.NoError(t, err)
	assert.Equal(t, "owner", ref.Owner)
	assert.Equal(t, "repo", ref.Name)
}
