// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package integration

import (
	"bytes"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"testing"
	"time"

	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/unittest"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/git/gitcmd"
	"code.gitea.io/gitea/modules/test"
	repo_service "code.gitea.io/gitea/services/repository"
	"code.gitea.io/gitea/tests"

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

func TestCompareTag(t *testing.T) {
	defer tests.PrepareTestEnv(t)()

	session := loginUser(t, "user2")
	req := NewRequest(t, "GET", "/user2/repo1/compare/v1.1...master")
	resp := session.MakeRequest(t, req, http.StatusOK)
	htmlDoc := NewHTMLParser(t, resp.Body)
	selection := htmlDoc.doc.Find(".ui.dropdown.select-branch")
	// A dropdown for both base and head.
	assert.Lenf(t, selection.Nodes, 2, "The template has changed")

	req = NewRequest(t, "GET", "/user2/repo1/compare/invalid").SetHeader("Accept", "text/html")
	resp = session.MakeRequest(t, req, http.StatusNotFound)
	assert.True(t, test.IsNormalPageCompleted(resp.Body.String()), "expect 404 page not 500")
}

// Compare with inferred default branch (master)
func TestCompareDefault(t *testing.T) {
	defer tests.PrepareTestEnv(t)()

	session := loginUser(t, "user2")
	req := NewRequest(t, "GET", "/user2/repo1/compare/v1.1")
	resp := session.MakeRequest(t, req, http.StatusOK)
	htmlDoc := NewHTMLParser(t, resp.Body)
	selection := htmlDoc.doc.Find(".ui.dropdown.select-branch")
	assert.Lenf(t, selection.Nodes, 2, "The template has changed")
}

// Ensure the comparison matches what we expect
func inspectCompare(t *testing.T, htmlDoc *HTMLDoc, diffCount int, diffChanges []string) {
	selection := htmlDoc.doc.Find("#diff-file-boxes").Children()

	assert.Lenf(t, selection.Nodes, diffCount, "Expected %v diffed files, found: %v", diffCount, len(selection.Nodes))

	for _, diffChange := range diffChanges {
		selection = htmlDoc.doc.Find(fmt.Sprintf("[data-new-filename=\"%s\"]", diffChange))
		assert.Lenf(t, selection.Nodes, 1, "Expected 1 match for [data-new-filename=\"%s\"], found: %v", diffChange, len(selection.Nodes))
	}
}

// Git commit graph for repo20
// * 8babce9 (origin/remove-files-b) Add a dummy file
// * b67e43a Delete test.csv and link_hi
// | * cfe3b3c (origin/remove-files-a) Delete test.csv and link_hi
// |/
// * c8e31bc (origin/add-csv) Add test csv file
// * 808038d (HEAD -> master, origin/master, origin/HEAD) Added test links

func TestCompareBranches(t *testing.T) {
	defer tests.PrepareTestEnv(t)()

	session := loginUser(t, "user2")

	// Indirect compare remove-files-b (head) with add-csv (base) branch
	//
	//	'link_hi' and 'test.csv' are deleted, 'test.txt' is added
	req := NewRequest(t, "GET", "/user2/repo20/compare/add-csv...remove-files-b")
	resp := session.MakeRequest(t, req, http.StatusOK)
	htmlDoc := NewHTMLParser(t, resp.Body)

	diffCount := 3
	diffChanges := []string{"link_hi", "test.csv", "test.txt"}

	inspectCompare(t, htmlDoc, diffCount, diffChanges)

	// Indirect compare remove-files-b (head) with remove-files-a (base) branch
	//
	//	'link_hi' and 'test.csv' are deleted, 'test.txt' is added

	req = NewRequest(t, "GET", "/user2/repo20/compare/remove-files-a...remove-files-b")
	resp = session.MakeRequest(t, req, http.StatusOK)
	htmlDoc = NewHTMLParser(t, resp.Body)

	diffCount = 3
	diffChanges = []string{"link_hi", "test.csv", "test.txt"}

	inspectCompare(t, htmlDoc, diffCount, diffChanges)

	// Indirect compare remove-files-a (head) with remove-files-b (base) branch
	//
	//	'link_hi' and 'test.csv' are deleted

	req = NewRequest(t, "GET", "/user2/repo20/compare/remove-files-b...remove-files-a")
	resp = session.MakeRequest(t, req, http.StatusOK)
	htmlDoc = NewHTMLParser(t, resp.Body)

	diffCount = 2
	diffChanges = []string{"link_hi", "test.csv"}

	inspectCompare(t, htmlDoc, diffCount, diffChanges)

	// Direct compare remove-files-b (head) with remove-files-a (base) branch
	//
	//	'test.txt' is deleted

	req = NewRequest(t, "GET", "/user2/repo20/compare/remove-files-b..remove-files-a")
	resp = session.MakeRequest(t, req, http.StatusOK)
	htmlDoc = NewHTMLParser(t, resp.Body)

	diffCount = 1
	diffChanges = []string{"test.txt"}

	inspectCompare(t, htmlDoc, diffCount, diffChanges)
}

func createUnrelatedBranch(t *testing.T, repo *repo_model.Repository, user *user_model.User, branchName string) {
	t.Helper()

	repoPath := repo_model.RepoPath(user.Name, repo.Name)
	require.NoError(t, gitcmd.NewCommand("read-tree", "--empty").WithDir(repoPath).Run(t.Context()))

	stdout, _, err := gitcmd.NewCommand("hash-object", "-w", "--stdin").
		WithDir(repoPath).
		WithStdinBytes([]byte("Unrelated File")).
		RunStdString(t.Context())
	require.NoError(t, err)
	blobSHA := strings.TrimSpace(stdout)

	_, _, err = gitcmd.NewCommand("update-index", "--add", "--replace", "--cacheinfo").
		AddDynamicArguments("100644", blobSHA, "unrelated.txt").
		WithDir(repoPath).
		RunStdString(t.Context())
	require.NoError(t, err)

	stdout, _, err = gitcmd.NewCommand("write-tree").WithDir(repoPath).RunStdString(t.Context())
	require.NoError(t, err)
	treeSHA := strings.TrimSpace(stdout)

	commitTimeStr := time.Now().Format(time.RFC3339)
	doerSig := user.NewGitSig()
	env := append(os.Environ(),
		"GIT_AUTHOR_NAME="+doerSig.Name,
		"GIT_AUTHOR_EMAIL="+doerSig.Email,
		"GIT_AUTHOR_DATE="+commitTimeStr,
		"GIT_COMMITTER_NAME="+doerSig.Name,
		"GIT_COMMITTER_EMAIL="+doerSig.Email,
		"GIT_COMMITTER_DATE="+commitTimeStr,
	)

	messageBytes := bytes.NewBufferString("Unrelated\n")
	stdout, _, err = gitcmd.NewCommand("commit-tree").AddDynamicArguments(treeSHA).
		WithEnv(env).
		WithDir(repoPath).
		WithStdinBytes(messageBytes.Bytes()).
		RunStdString(t.Context())
	require.NoError(t, err)
	commitSHA := strings.TrimSpace(stdout)

	_, _, err = gitcmd.NewCommand("branch").AddDynamicArguments(branchName, commitSHA).
		WithDir(repoPath).
		RunStdString(t.Context())
	require.NoError(t, err)
}

func TestCompareBranchesNoCommonMergeBase(t *testing.T) {
	defer tests.PrepareTestEnv(t)()

	user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"})
	repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user2.ID, Name: "repo1"})
	createUnrelatedBranch(t, repo1, user2, "unrelated-history")

	session := loginUser(t, "user2")
	req := NewRequest(t, "GET", "/user2/repo1/compare/master...unrelated-history")
	resp := session.MakeRequest(t, req, http.StatusOK)
	body := resp.Body.String()
	htmlDoc := NewHTMLParser(t, resp.Body)

	selection := htmlDoc.doc.Find(".ui.dropdown.select-branch")
	assert.Lenf(t, selection.Nodes, 2, "The template has changed")
	assert.Contains(t, body, "These branches do not share a common merge base")
	assert.Equal(t, 1, htmlDoc.doc.Find(`a.item[href="/user2/repo1/compare/master...unrelated-history"]`).Length())
	assert.Equal(t, 1, htmlDoc.doc.Find(`a.item[href="/user2/repo1/compare/master...master"]`).Length())
	assert.Equal(t, 0, htmlDoc.doc.Find(".pullrequest-form").Length())
}

func TestCompareCodeExpand(t *testing.T) {
	onGiteaRun(t, func(t *testing.T, u *url.URL) {
		user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
		repo, err := repo_service.CreateRepositoryDirectly(t.Context(), user1, user1, repo_service.CreateRepoOptions{
			Name:          "test_blob_excerpt",
			Readme:        "Default",
			AutoInit:      true,
			DefaultBranch: "main",
		}, true)
		assert.NoError(t, err)

		session := loginUser(t, user1.Name)
		testEditFile(t, session, user1.Name, repo.Name, "main", "README.md", strings.Repeat("a\n", 30))

		user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
		session = loginUser(t, user2.Name)
		testRepoFork(t, session, user1.Name, repo.Name, user2.Name, "test_blob_excerpt-fork", "")
		testCreateBranch(t, session, user2.Name, "test_blob_excerpt-fork", "branch/main", "forked-branch", http.StatusSeeOther)
		testEditFile(t, session, user2.Name, "test_blob_excerpt-fork", "forked-branch", "README.md", strings.Repeat("a\n", 15)+"CHANGED\n"+strings.Repeat("a\n", 15))

		req := NewRequest(t, "GET", "/user1/test_blob_excerpt/compare/main...user2/test_blob_excerpt-fork:forked-branch")
		resp := session.MakeRequest(t, req, http.StatusOK)
		htmlDoc := NewHTMLParser(t, resp.Body)
		els := htmlDoc.Find(`button.code-expander-button[hx-get]`)

		// all the links in the comparison should be to the forked repo&branch
		assert.NotZero(t, els.Length())
		for i := 0; i < els.Length(); i++ {
			link := els.Eq(i).AttrOr("hx-get", "")
			assert.True(t, strings.HasPrefix(link, "/user2/test_blob_excerpt-fork/blob_excerpt/"))
		}
	})
}
