package scm_provider

import (
	"errors"
	"fmt"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"

	"github.com/microsoft/azure-devops-go-api/azuredevops/v7"
	azureGit "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"

	azureMock "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/azure_devops/git/mocks"
	"github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/mocks"
)

func TestAzureDevopsRepoHasPath(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"
	repoName := "myorg_project_repo"
	path := "dir/subdir/item.yaml"
	branchName := "my/featurebranch"

	ctx := t.Context()
	uuid := uuid.New().String()

	testCases := []struct {
		name             string
		pathFound        bool
		azureDevopsError error
		returnError      bool
		errorMessage     string
		clientError      error
	}{
		{
			name:        "RepoHasPath when Azure DevOps client factory fails returns error",
			clientError: errors.New("Client factory error"),
		},
		{
			name:      "RepoHasPath when found returns true",
			pathFound: true,
		},
		{
			name:             "RepoHasPath when no path found returns false",
			pathFound:        false,
			azureDevopsError: azuredevops.WrappedError{TypeKey: new(AzureDevOpsErrorsTypeKeyValues.GitItemNotFound)},
		},
		{
			name:             "RepoHasPath when unknown Azure DevOps WrappedError occurs returns error",
			pathFound:        false,
			azureDevopsError: azuredevops.WrappedError{TypeKey: new("OtherAzureDevopsException")},
			returnError:      true,
			errorMessage:     "failed to check for path existence",
		},
		{
			name:             "RepoHasPath when unknown Azure DevOps error occurs returns error",
			pathFound:        false,
			azureDevopsError: errors.New("Undefined error from Azure Devops"),
			returnError:      true,
			errorMessage:     "failed to check for path existence",
		},
		{
			name:             "RepoHasPath when wrapped Azure DevOps error occurs without TypeKey returns error",
			pathFound:        false,
			azureDevopsError: azuredevops.WrappedError{},
			returnError:      true,
			errorMessage:     "failed to check for path existence",
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			gitClientMock := &azureMock.Client{}

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, testCase.clientError)

			repoId := &uuid
			gitClientMock.EXPECT().GetItem(mock.Anything, azureGit.GetItemArgs{Project: &teamProject, Path: &path, VersionDescriptor: &azureGit.GitVersionDescriptor{Version: &branchName}, RepositoryId: repoId}).Return(nil, testCase.azureDevopsError)

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock}

			repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: branchName}
			hasPath, err := provider.RepoHasPath(ctx, repo, path)

			if testCase.clientError != nil {
				require.ErrorContains(t, err, testCase.clientError.Error())
				gitClientMock.AssertNotCalled(t, "GetItem", ctx, azureGit.GetItemArgs{Project: &teamProject, Path: &path, VersionDescriptor: &azureGit.GitVersionDescriptor{Version: &branchName}, RepositoryId: repoId})

				return
			}

			if testCase.returnError {
				require.ErrorContains(t, err, testCase.errorMessage)
			}

			assert.Equal(t, testCase.pathFound, hasPath)

			gitClientMock.AssertCalled(t, "GetItem", ctx, azureGit.GetItemArgs{Project: &teamProject, Path: &path, VersionDescriptor: &azureGit.GitVersionDescriptor{Version: &branchName}, RepositoryId: repoId})
		})
	}
}

func TestGetDefaultBranchOnDisabledRepo(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"
	repoName := "myorg_project_repo"
	defaultBranch := "main"

	ctx := t.Context()

	testCases := []struct {
		name              string
		azureDevOpsError  error
		shouldReturnError bool
	}{
		{
			name:              "azure devops error when disabled repo causes empty return value",
			azureDevOpsError:  azuredevops.WrappedError{TypeKey: new(AzureDevOpsErrorsTypeKeyValues.GitRepositoryNotFound)},
			shouldReturnError: false,
		},
		{
			name:              "azure devops error with unknown error type returns error",
			azureDevOpsError:  azuredevops.WrappedError{TypeKey: new("OtherError")},
			shouldReturnError: true,
		},
		{
			name:              "other error when calling azure devops returns error",
			azureDevOpsError:  errors.New("some unknown error"),
			shouldReturnError: true,
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			uuid := uuid.New().String()

			gitClientMock := azureMock.NewClient(t)

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, nil)

			gitClientMock.EXPECT().GetBranch(mock.Anything, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch}).Return(nil, testCase.azureDevOpsError)

			repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: defaultBranch}

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock, allBranches: false}
			branches, err := provider.GetBranches(ctx, repo)

			if testCase.shouldReturnError {
				require.Error(t, err)
			} else {
				require.NoError(t, err)
			}

			assert.Empty(t, branches)
		})
	}
}

func TestGetAllBranchesOnDisabledRepo(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"
	repoName := "myorg_project_repo"
	defaultBranch := "main"

	ctx := t.Context()

	testCases := []struct {
		name              string
		azureDevOpsError  error
		shouldReturnError bool
	}{
		{
			name:              "azure devops error when disabled repo causes empty return value",
			azureDevOpsError:  azuredevops.WrappedError{TypeKey: new(AzureDevOpsErrorsTypeKeyValues.GitRepositoryNotFound)},
			shouldReturnError: false,
		},
		{
			name:              "azure devops error with unknown error type returns error",
			azureDevOpsError:  azuredevops.WrappedError{TypeKey: new("OtherError")},
			shouldReturnError: true,
		},
		{
			name:              "other error when calling azure devops returns error",
			azureDevOpsError:  errors.New("some unknown error"),
			shouldReturnError: true,
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			uuid := uuid.New().String()

			gitClientMock := azureMock.NewClient(t)

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, nil)

			gitClientMock.EXPECT().GetBranches(mock.Anything, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject}).Return(nil, testCase.azureDevOpsError)

			repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: defaultBranch}

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock, allBranches: true}
			branches, err := provider.GetBranches(ctx, repo)

			if testCase.shouldReturnError {
				require.Error(t, err)
			} else {
				require.NoError(t, err)
			}

			assert.Empty(t, branches)
		})
	}
}

func TestAzureDevOpsGetDefaultBranchStripsRefsName(t *testing.T) {
	t.Parallel()
	t.Run("Get branches only default branch removes characters before querying azure devops", func(t *testing.T) {
		t.Parallel()
		organization := "myorg"
		teamProject := "myorg_project"
		repoName := "myorg_project_repo"

		ctx := t.Context()
		uuid := uuid.New().String()
		strippedBranchName := "somebranch"
		defaultBranch := fmt.Sprintf("refs/heads/%v", strippedBranchName)

		branchReturn := &azureGit.GitBranchStats{Name: &strippedBranchName, Commit: &azureGit.GitCommitRef{CommitId: new("abc123233223")}}
		repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: defaultBranch}

		gitClientMock := &azureMock.Client{}

		clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
		clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, nil)

		gitClientMock.EXPECT().GetBranch(mock.Anything, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &strippedBranchName}).Return(branchReturn, nil).Maybe()

		provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock, allBranches: false}
		branches, err := provider.GetBranches(ctx, repo)

		require.NoError(t, err)
		assert.Len(t, branches, 1)
		assert.Equal(t, strippedBranchName, branches[0].Branch)

		gitClientMock.AssertCalled(t, "GetBranch", ctx, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &strippedBranchName})
	})
}

func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"
	repoName := "myorg_project_repo"

	ctx := t.Context()
	uuid := uuid.New().String()

	defaultBranch := "main"

	testCases := []struct {
		name                string
		expectedBranch      *azureGit.GitBranchStats
		getBranchesAPIError error
		clientError         error
	}{
		{
			name:           "GetBranches AllBranches false when single branch returned returns branch",
			expectedBranch: &azureGit.GitBranchStats{Name: &defaultBranch, Commit: &azureGit.GitCommitRef{CommitId: new("abc123233223")}},
		},
		{
			name:                "GetBranches AllBranches false when request fails returns error and empty result",
			getBranchesAPIError: errors.New("Remote Azure Devops GetBranches error"),
		},
		{
			name:        "GetBranches AllBranches false when Azure DevOps client fails returns error",
			clientError: errors.New("Could not get Azure Devops API client"),
		},
		{
			name:           "GetBranches AllBranches false when branch returned with long commit SHA",
			expectedBranch: &azureGit.GitBranchStats{Name: &defaultBranch, Commit: &azureGit.GitCommitRef{CommitId: new("53863052ADF24229AB72154B4D83DAB7")}},
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			gitClientMock := &azureMock.Client{}

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, testCase.clientError)

			gitClientMock.EXPECT().GetBranch(mock.Anything, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch}).Return(testCase.expectedBranch, testCase.getBranchesAPIError)

			repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: defaultBranch}

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock, allBranches: false}
			branches, err := provider.GetBranches(ctx, repo)

			if testCase.clientError != nil {
				require.ErrorContains(t, err, testCase.clientError.Error())
				gitClientMock.AssertNotCalled(t, "GetBranch", ctx, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch})

				return
			}

			if testCase.getBranchesAPIError != nil {
				assert.Empty(t, branches)
				require.ErrorContains(t, err, testCase.getBranchesAPIError.Error())
			} else {
				if testCase.expectedBranch != nil {
					assert.NotEmpty(t, branches)
				}
				assert.Len(t, branches, 1)
				assert.Equal(t, repo.RepositoryId, branches[0].RepositoryId)
			}

			gitClientMock.AssertCalled(t, "GetBranch", ctx, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch})
		})
	}
}

func TestAzureDevopsGetBranches(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"
	repoName := "myorg_project_repo"

	ctx := t.Context()
	uuid := uuid.New().String()

	testCases := []struct {
		name                       string
		expectedBranches           *[]azureGit.GitBranchStats
		getBranchesAPIError        error
		clientError                error
		allBranches                bool
		expectedProcessingErrorMsg string
	}{
		{
			name:             "GetBranches when single branch returned returns this branch info",
			expectedBranches: &[]azureGit.GitBranchStats{{Name: new("feature-feat1"), Commit: &azureGit.GitCommitRef{CommitId: new("abc123233223")}}},
			allBranches:      true,
		},
		{
			name:                "GetBranches when Azure DevOps request fails returns error and empty result",
			getBranchesAPIError: errors.New("Remote Azure Devops GetBranches error"),
			allBranches:         true,
		},
		{
			name:                       "GetBranches when no branches returned returns error",
			allBranches:                true,
			expectedProcessingErrorMsg: "empty branch result",
		},
		{
			name:        "GetBranches when git client retrievel fails returns error",
			clientError: errors.New("Could not get Azure Devops API client"),
			allBranches: true,
		},
		{
			name: "GetBranches when multiple branches returned returns branch info for all branches",
			expectedBranches: &[]azureGit.GitBranchStats{
				{Name: new("feature-feat1"), Commit: &azureGit.GitCommitRef{CommitId: new("abc123233223")}},
				{Name: new("feature/feat2"), Commit: &azureGit.GitCommitRef{CommitId: new("4334")}},
				{Name: new("feature/feat2"), Commit: &azureGit.GitCommitRef{CommitId: new("53863052ADF24229AB72154B4D83DAB7")}},
			},
			allBranches: true,
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			gitClientMock := &azureMock.Client{}

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, testCase.clientError)

			gitClientMock.EXPECT().GetBranches(mock.Anything, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject}).Return(testCase.expectedBranches, testCase.getBranchesAPIError)

			repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid}

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock, allBranches: testCase.allBranches}
			branches, err := provider.GetBranches(ctx, repo)

			if testCase.expectedProcessingErrorMsg != "" {
				require.ErrorContains(t, err, testCase.expectedProcessingErrorMsg)
				assert.Nil(t, branches)

				return
			}
			if testCase.clientError != nil {
				require.ErrorContains(t, err, testCase.clientError.Error())
				gitClientMock.AssertNotCalled(t, "GetBranches", ctx, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject})
				return
			}

			if testCase.getBranchesAPIError != nil {
				assert.Empty(t, branches)
				require.ErrorContains(t, err, testCase.getBranchesAPIError.Error())
			} else {
				if len(*testCase.expectedBranches) > 0 {
					assert.NotEmpty(t, branches)
				}
				assert.Len(t, branches, len(*testCase.expectedBranches))
				for _, branch := range branches {
					assert.NotEmpty(t, branch.RepositoryId)
					assert.Equal(t, repo.RepositoryId, branch.RepositoryId)
				}
			}

			gitClientMock.AssertCalled(t, "GetBranches", ctx, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject})
		})
	}
}

func TestGetAzureDevopsRepositories(t *testing.T) {
	t.Parallel()
	organization := "myorg"
	teamProject := "myorg_project"

	uuid := uuid.New()

	repoId := &uuid

	testCases := []struct {
		name                  string
		getRepositoriesError  error
		repositories          []azureGit.GitRepository
		expectedNumberOfRepos int
	}{
		{
			name:                  "ListRepos when single repo found returns repo info",
			repositories:          []azureGit.GitRepository{{Name: new("repo1"), DefaultBranch: new("main"), RemoteUrl: new("https://remoteurl.u"), Id: repoId}},
			expectedNumberOfRepos: 1,
		},
		{
			name:         "ListRepos when repo has no default branch returns empty list",
			repositories: []azureGit.GitRepository{{Name: new("repo2"), RemoteUrl: new("https://remoteurl.u"), Id: repoId}},
		},
		{
			name:                 "ListRepos when Azure DevOps request fails returns error",
			getRepositoriesError: errors.New("Could not get repos"),
		},
		{
			name:         "ListRepos when repo has no name returns empty list",
			repositories: []azureGit.GitRepository{{DefaultBranch: new("main"), RemoteUrl: new("https://remoteurl.u"), Id: repoId}},
		},
		{
			name:         "ListRepos when repo has no remote URL returns empty list",
			repositories: []azureGit.GitRepository{{DefaultBranch: new("main"), Name: new("repo_name"), Id: repoId}},
		},
		{
			name:         "ListRepos when repo has no ID returns empty list",
			repositories: []azureGit.GitRepository{{DefaultBranch: new("main"), Name: new("repo_name"), RemoteUrl: new("https://remoteurl.u")}},
		},
		{
			name: "ListRepos when multiple repos returned returns list of eligible repos only",
			repositories: []azureGit.GitRepository{
				{Name: new("returned1"), DefaultBranch: new("main"), RemoteUrl: new("https://remoteurl.u"), Id: repoId},
				{Name: new("missing_default_branch"), RemoteUrl: new("https://remoteurl.u"), Id: repoId},
				{DefaultBranch: new("missing_name"), RemoteUrl: new("https://remoteurl.u"), Id: repoId},
				{Name: new("missing_remote_url"), DefaultBranch: new("main"), Id: repoId},
				{Name: new("missing_id"), DefaultBranch: new("main"), RemoteUrl: new("https://remoteurl.u")},
			},
			expectedNumberOfRepos: 1,
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			gitClientMock := azureMock.NewClient(t)
			gitClientMock.EXPECT().GetRepositories(mock.Anything, azureGit.GetRepositoriesArgs{Project: new(teamProject)}).Return(&testCase.repositories, testCase.getRepositoriesError)

			clientFactoryMock := &mocks.AzureDevOpsClientFactory{}
			clientFactoryMock.EXPECT().GetClient(mock.Anything).Return(gitClientMock, nil)

			provider := AzureDevOpsProvider{organization: organization, teamProject: teamProject, clientFactory: clientFactoryMock}

			repositories, err := provider.ListRepos(t.Context(), "https")

			if testCase.getRepositoriesError != nil {
				require.Error(t, err, "Expected an error from test case %v", testCase.name)
			}

			if testCase.expectedNumberOfRepos == 0 {
				assert.Empty(t, repositories)
			} else {
				assert.NotEmpty(t, repositories)
				assert.Len(t, repositories, testCase.expectedNumberOfRepos)
			}
		})
	}
}
