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

package integration

import (
	"fmt"
	"net/http"
	"strconv"
	"testing"

	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/models/unittest"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/test"
	test_utils "code.gitea.io/gitea/modules/test"
	"code.gitea.io/gitea/tests"

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

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

	session := loginUser(t, "user1")
	req := NewRequest(t, "GET", "/-/admin/users")
	session.MakeRequest(t, req, http.StatusOK)

	session = loginUser(t, "user2")
	req = NewRequest(t, "GET", "/-/admin/users")
	session.MakeRequest(t, req, http.StatusForbidden)
}

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

	session := loginUser(t, "user1")
	req := NewRequest(t, "GET", "/-/admin/users/1")
	session.MakeRequest(t, req, http.StatusOK)

	session = loginUser(t, "user2")
	req = NewRequest(t, "GET", "/-/admin/users/1")
	session.MakeRequest(t, req, http.StatusForbidden)
}

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

	testSuccessfulEdit(t, user_model.User{ID: 2, Name: "newusername", LoginName: "otherlogin", Email: "new@e-mail.gitea"})
}

func TestAdminCannotEditSuperAdminUser(t *testing.T) {
	defer tests.PrepareTestEnv(t)()
	defer test.MockVariableValue(&setting.Admin.SuperAdminEnabled, true)()

	user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
	user2.IsAdmin = true
	_, err := db.GetEngine(t.Context()).ID(user2.ID).Cols("is_admin").Update(user2)
	require.NoError(t, err)
	require.NoError(t, user_model.SetUserSetting(t.Context(), 1, user_model.SettingsKeySuperAdminEnabled, "true"))

	session := loginUser(t, "user2")

	resp := session.MakeRequest(t, NewRequest(t, "GET", "/-/admin/users/1/edit"), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/1", resp.Header().Get("Location"))

	resp = session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/users/1/edit", map[string]string{
		"user_name":      "user1",
		"login_name":     "user1",
		"login_type":     "0-0",
		"email":          "user1@example.com",
		"prohibit_login": "on",
		"restricted":     "on",
	}), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/1", resp.Header().Get("Location"))

	user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
	assert.False(t, user1.ProhibitLogin)
	assert.False(t, user1.IsRestricted)
}

func testSuccessfulEdit(t *testing.T, formData user_model.User) {
	makeRequest(t, formData, http.StatusSeeOther)
}

func makeRequest(t *testing.T, formData user_model.User, headerCode int) {
	session := loginUser(t, "user1")
	req := NewRequestWithValues(t, "POST", "/-/admin/users/"+strconv.Itoa(int(formData.ID))+"/edit", map[string]string{
		"user_name":  formData.Name,
		"login_name": formData.LoginName,
		"login_type": "0-0",
		"email":      formData.Email,
	})

	session.MakeRequest(t, req, headerCode)
	user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: formData.ID})
	assert.Equal(t, formData.Name, user.Name)
	assert.Equal(t, formData.LoginName, user.LoginName)
	assert.Equal(t, formData.Email, user.Email)
}

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

	session := loginUser(t, "user1")

	usersToDelete := []struct {
		userID int64
		purge  bool
	}{
		{
			userID: 2,
			purge:  true,
		},
		{
			userID: 8,
		},
	}

	for _, entry := range usersToDelete {
		t.Run(fmt.Sprintf("DeleteUser%d", entry.userID), func(t *testing.T) {
			user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: entry.userID})
			assert.NotNil(t, user)

			var query string
			if entry.purge {
				query = "?purge=true"
			}

			req := NewRequest(t, "POST", fmt.Sprintf("/-/admin/users/%d/delete%s", entry.userID, query))
			session.MakeRequest(t, req, http.StatusSeeOther)

			assertUserDeleted(t, entry.userID)
			unittest.CheckConsistencyFor(t, &user_model.User{})
		})
	}
}

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

	session := loginUser(t, "user1")
	user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
	assert.NotNil(t, user)

	req := NewRequestWithValues(t, "POST", "/-/admin/users/2/delete", map[string]string{
		"inline": "1",
		"purge":  "true",
	})
	resp := session.MakeRequest(t, req, http.StatusOK)

	redirect := test_utils.ParseJSONRedirect(resp.Body.Bytes())
	assert.Equal(t, "/-/admin/users", redirect.Redirect)
	assertUserDeleted(t, 2)
}

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

	for _, userID := range []int64{2, 4, 8} {
		user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID})
		user.IsAdmin = true
		_, err := db.GetEngine(t.Context()).ID(userID).Cols("is_admin").Update(user)
		require.NoError(t, err)
	}
	require.NoError(t, user_model.SetUserSetting(t.Context(), 2, user_model.SettingsKeyAdminGrantedBy, "4"))
	require.NoError(t, user_model.SetUserSetting(t.Context(), 2, user_model.SettingsKeyAdminGrantedByName, "user4"))
	require.NoError(t, user_model.SetUserSetting(t.Context(), 2, user_model.SettingsKeyAdminGrantedByEmail, "user4@example.com"))

	session := loginUser(t, "user2")

	resp := session.MakeRequest(t, NewRequest(t, "POST", "/-/admin/users/8/delete?purge=true"), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users", resp.Header().Get("Location"))
	assertUserDeleted(t, 8)

	resp = session.MakeRequest(t, NewRequest(t, "POST", "/-/admin/users/4/delete"), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/4", resp.Header().Get("Location"))
	unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
}

func TestAdminGrantorOnlyCanEditGrantedAdmin(t *testing.T) {
	defer tests.PrepareTestEnv(t)()
	defer test.MockVariableValue(&setting.Admin.AdminManagementPolicy, setting.AdminManagementPolicyGrantorOnly)()

	makeAdminUser(t, 2)
	makeAdminUser(t, 4)
	makeAdminUser(t, 8)
	setAdminGrantor(t, 2, 4, "user4", "user4@example.com")

	session := loginUser(t, "user4")
	resp := session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/users/2/edit", map[string]string{
		"user_name":  "user2",
		"login_name": "user2",
		"login_type": "0-0",
		"email":      "grantor@example.com",
	}), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/2", resp.Header().Get("Location"))

	user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
	assert.Equal(t, "grantor@example.com", user2.Email)

	session = loginUser(t, "user8")
	resp = session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/users/2/edit", map[string]string{
		"user_name":  "user2",
		"login_name": "user2",
		"login_type": "0-0",
		"email":      "blocked@example.com",
	}), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/2", resp.Header().Get("Location"))

	user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
	assert.Equal(t, "grantor@example.com", user2.Email)
}

func TestAdminGrantorInheritanceUsesParentGrantor(t *testing.T) {
	defer tests.PrepareTestEnv(t)()
	defer test.MockVariableValue(&setting.Admin.AdminManagementPolicy, setting.AdminManagementPolicyGrantorInheritance)()

	makeAdminUser(t, 2)
	makeAdminUser(t, 4)
	makeAdminUser(t, 8)
	setAdminGrantor(t, 2, 4, "user4", "user4@example.com")
	setAdminGrantor(t, 4, 8, "user8", "user8@example.com")

	user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
	user4.ProhibitLogin = true
	_, err := db.GetEngine(t.Context()).ID(user4.ID).Cols("prohibit_login").Update(user4)
	require.NoError(t, err)

	session := loginUser(t, "user8")
	resp := session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/users/2/edit", map[string]string{
		"user_name":  "user2",
		"login_name": "user2",
		"login_type": "0-0",
		"email":      "inherited@example.com",
	}), http.StatusSeeOther)
	assert.Equal(t, "/-/admin/users/2", resp.Header().Get("Location"))

	user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
	assert.Equal(t, "inherited@example.com", user2.Email)
}

func makeAdminUser(t *testing.T, userID int64) {
	user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID})
	user.IsAdmin = true
	_, err := db.GetEngine(t.Context()).ID(userID).Cols("is_admin").Update(user)
	require.NoError(t, err)
}

func setAdminGrantor(t *testing.T, userID, grantorID int64, grantorName, grantorEmail string) {
	require.NoError(t, user_model.SetUserSetting(t.Context(), userID, user_model.SettingsKeyAdminGrantedBy, strconv.FormatInt(grantorID, 10)))
	require.NoError(t, user_model.SetUserSetting(t.Context(), userID, user_model.SettingsKeyAdminGrantedByName, grantorName))
	require.NoError(t, user_model.SetUserSetting(t.Context(), userID, user_model.SettingsKeyAdminGrantedByEmail, grantorEmail))
}
