package backups

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"

	"databasus-backend/internal/config"
	audit_logs "databasus-backend/internal/features/audit_logs"
	backups_core "databasus-backend/internal/features/backups/backups/core"
	backups_download "databasus-backend/internal/features/backups/backups/download"
	backups_config "databasus-backend/internal/features/backups/config"
	"databasus-backend/internal/features/databases"
	"databasus-backend/internal/features/databases/databases/postgresql"
	"databasus-backend/internal/features/storages"
	local_storage "databasus-backend/internal/features/storages/models/local"
	users_dto "databasus-backend/internal/features/users/dto"
	users_enums "databasus-backend/internal/features/users/enums"
	users_services "databasus-backend/internal/features/users/services"
	users_testing "databasus-backend/internal/features/users/testing"
	workspaces_models "databasus-backend/internal/features/workspaces/models"
	workspaces_testing "databasus-backend/internal/features/workspaces/testing"
	"databasus-backend/internal/util/encryption"
	test_utils "databasus-backend/internal/util/testing"
	"databasus-backend/internal/util/tools"
)

func Test_GetBackups_PermissionsEnforced(t *testing.T) {
	tests := []struct {
		name               string
		workspaceRole      *users_enums.WorkspaceRole
		isGlobalAdmin      bool
		expectSuccess      bool
		expectedStatusCode int
	}{
		{
			name:               "workspace viewer can get backups",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleViewer; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "workspace member can get backups",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleMember; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "non-member cannot get backups",
			workspaceRole:      nil,
			isGlobalAdmin:      false,
			expectSuccess:      false,
			expectedStatusCode: http.StatusBadRequest,
		},
		{
			name:               "global admin can get backups",
			workspaceRole:      nil,
			isGlobalAdmin:      true,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			router := createTestRouter()
			owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
			workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

			database, _, storage := createTestDatabaseWithBackups(workspace, owner, router)

			var testUserToken string
			if tt.isGlobalAdmin {
				admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)
				testUserToken = admin.Token
			} else if tt.workspaceRole != nil {
				if *tt.workspaceRole == users_enums.WorkspaceRoleOwner {
					testUserToken = owner.Token
				} else {
					member := users_testing.CreateTestUser(users_enums.UserRoleMember)
					workspaces_testing.AddMemberToWorkspace(
						workspace,
						member,
						*tt.workspaceRole,
						owner.Token,
						router,
					)
					testUserToken = member.Token
				}
			} else {
				nonMember := users_testing.CreateTestUser(users_enums.UserRoleMember)
				testUserToken = nonMember.Token
			}

			testResp := test_utils.MakeGetRequest(
				t,
				router,
				fmt.Sprintf("/api/v1/backups?database_id=%s", database.ID.String()),
				"Bearer "+testUserToken,
				tt.expectedStatusCode,
			)

			if tt.expectSuccess {
				var response GetBackupsResponse
				err := json.Unmarshal(testResp.Body, &response)
				assert.NoError(t, err)
				assert.GreaterOrEqual(t, len(response.Backups), 1)
				assert.GreaterOrEqual(t, response.Total, int64(1))
			} else {
				assert.Contains(t, string(testResp.Body), "insufficient permissions")
			}

			// Cleanup
			databases.RemoveTestDatabase(database)
			time.Sleep(50 * time.Millisecond)
			storages.RemoveTestStorage(storage.ID)
			workspaces_testing.RemoveTestWorkspace(workspace, router)
		})
	}
}

func Test_CreateBackup_PermissionsEnforced(t *testing.T) {
	tests := []struct {
		name               string
		workspaceRole      *users_enums.WorkspaceRole
		isGlobalAdmin      bool
		expectSuccess      bool
		expectedStatusCode int
	}{
		{
			name:               "workspace owner can create backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleOwner; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "workspace member can create backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleMember; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "workspace viewer can create backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleViewer; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "non-member cannot create backup",
			workspaceRole:      nil,
			isGlobalAdmin:      false,
			expectSuccess:      false,
			expectedStatusCode: http.StatusBadRequest,
		},
		{
			name:               "global admin can create backup",
			workspaceRole:      nil,
			isGlobalAdmin:      true,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			router := createTestRouter()
			owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
			workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

			database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)
			enableBackupForDatabase(database.ID)

			var testUserToken string
			if tt.isGlobalAdmin {
				admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)
				testUserToken = admin.Token
			} else if tt.workspaceRole != nil {
				if *tt.workspaceRole == users_enums.WorkspaceRoleOwner {
					testUserToken = owner.Token
				} else {
					member := users_testing.CreateTestUser(users_enums.UserRoleMember)
					workspaces_testing.AddMemberToWorkspace(
						workspace,
						member,
						*tt.workspaceRole,
						owner.Token,
						router,
					)
					testUserToken = member.Token
				}
			} else {
				nonMember := users_testing.CreateTestUser(users_enums.UserRoleMember)
				testUserToken = nonMember.Token
			}

			request := MakeBackupRequest{DatabaseID: database.ID}
			testResp := test_utils.MakePostRequest(
				t,
				router,
				"/api/v1/backups",
				"Bearer "+testUserToken,
				request,
				tt.expectedStatusCode,
			)

			if tt.expectSuccess {
				assert.Contains(t, string(testResp.Body), "backup started successfully")
			} else {
				assert.Contains(t, string(testResp.Body), "insufficient permissions")
			}

			// Cleanup
			databases.RemoveTestDatabase(database)
			workspaces_testing.RemoveTestWorkspace(workspace, router)
		})
	}
}

func Test_CreateBackup_AuditLogWritten(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)
	enableBackupForDatabase(database.ID)

	request := MakeBackupRequest{DatabaseID: database.ID}
	test_utils.MakePostRequest(
		t,
		router,
		"/api/v1/backups",
		"Bearer "+owner.Token,
		request,
		http.StatusOK,
	)

	time.Sleep(100 * time.Millisecond)

	auditLogService := audit_logs.GetAuditLogService()
	auditLogs, err := auditLogService.GetWorkspaceAuditLogs(
		workspace.ID,
		&audit_logs.GetAuditLogsRequest{
			Limit:  100,
			Offset: 0,
		},
	)
	assert.NoError(t, err)

	found := false
	for _, log := range auditLogs.AuditLogs {
		if strings.Contains(log.Message, "Backup manually initiated") &&
			strings.Contains(log.Message, database.Name) {
			found = true
			break
		}
	}
	assert.True(t, found, "Audit log for backup creation not found")

	// Cleanup
	databases.RemoveTestDatabase(database)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DeleteBackup_PermissionsEnforced(t *testing.T) {
	tests := []struct {
		name               string
		workspaceRole      *users_enums.WorkspaceRole
		isGlobalAdmin      bool
		expectSuccess      bool
		expectedStatusCode int
	}{
		{
			name:               "workspace owner can delete backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleOwner; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusNoContent,
		},
		{
			name:               "workspace member can delete backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleMember; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusNoContent,
		},
		{
			name:               "workspace viewer cannot delete backup",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleViewer; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      false,
			expectedStatusCode: http.StatusBadRequest,
		},
		{
			name:               "non-member cannot delete backup",
			workspaceRole:      nil,
			isGlobalAdmin:      false,
			expectSuccess:      false,
			expectedStatusCode: http.StatusBadRequest,
		},
		{
			name:               "global admin can delete backup",
			workspaceRole:      nil,
			isGlobalAdmin:      true,
			expectSuccess:      true,
			expectedStatusCode: http.StatusNoContent,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			router := createTestRouter()
			owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
			workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

			database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

			var testUserToken string
			if tt.isGlobalAdmin {
				admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)
				testUserToken = admin.Token
			} else if tt.workspaceRole != nil {
				if *tt.workspaceRole == users_enums.WorkspaceRoleOwner {
					testUserToken = owner.Token
				} else {
					member := users_testing.CreateTestUser(users_enums.UserRoleMember)
					workspaces_testing.AddMemberToWorkspace(
						workspace,
						member,
						*tt.workspaceRole,
						owner.Token,
						router,
					)
					testUserToken = member.Token
				}
			} else {
				nonMember := users_testing.CreateTestUser(users_enums.UserRoleMember)
				testUserToken = nonMember.Token
			}

			testResp := test_utils.MakeDeleteRequest(
				t,
				router,
				fmt.Sprintf("/api/v1/backups/%s", backup.ID.String()),
				"Bearer "+testUserToken,
				tt.expectedStatusCode,
			)

			if !tt.expectSuccess {
				assert.Contains(t, string(testResp.Body), "insufficient permissions")
			} else {
				userService := users_services.GetUserService()
				ownerUser, err := userService.GetUserFromToken(owner.Token)
				assert.NoError(t, err)

				response, err := GetBackupService().GetBackups(ownerUser, database.ID, 10, 0)
				assert.NoError(t, err)
				assert.Equal(t, 0, len(response.Backups))
			}

			// Cleanup
			databases.RemoveTestDatabase(database)
			time.Sleep(50 * time.Millisecond)
			storages.RemoveTestStorage(storage.ID)
			workspaces_testing.RemoveTestWorkspace(workspace, router)
		})
	}
}

func Test_DeleteBackup_AuditLogWritten(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	test_utils.MakeDeleteRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s", backup.ID.String()),
		"Bearer "+owner.Token,
		http.StatusNoContent,
	)

	time.Sleep(100 * time.Millisecond)

	auditLogService := audit_logs.GetAuditLogService()
	auditLogs, err := auditLogService.GetWorkspaceAuditLogs(
		workspace.ID,
		&audit_logs.GetAuditLogsRequest{
			Limit:  100,
			Offset: 0,
		},
	)
	assert.NoError(t, err)

	found := false
	for _, log := range auditLogs.AuditLogs {
		if strings.Contains(log.Message, "Backup deleted") &&
			strings.Contains(log.Message, database.Name) {
			found = true
			break
		}
	}
	assert.True(t, found, "Audit log for backup deletion not found")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_GenerateDownloadToken_PermissionsEnforced(t *testing.T) {
	tests := []struct {
		name               string
		workspaceRole      *users_enums.WorkspaceRole
		isGlobalAdmin      bool
		expectSuccess      bool
		expectedStatusCode int
	}{
		{
			name:               "workspace viewer can generate token",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleViewer; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "workspace member can generate token",
			workspaceRole:      func() *users_enums.WorkspaceRole { r := users_enums.WorkspaceRoleMember; return &r }(),
			isGlobalAdmin:      false,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
		{
			name:               "non-member cannot generate token",
			workspaceRole:      nil,
			isGlobalAdmin:      false,
			expectSuccess:      false,
			expectedStatusCode: http.StatusBadRequest,
		},
		{
			name:               "global admin can generate token",
			workspaceRole:      nil,
			isGlobalAdmin:      true,
			expectSuccess:      true,
			expectedStatusCode: http.StatusOK,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			router := createTestRouter()
			owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
			workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

			database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

			var testUserToken string
			if tt.isGlobalAdmin {
				admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)
				testUserToken = admin.Token
			} else if tt.workspaceRole != nil {
				if *tt.workspaceRole == users_enums.WorkspaceRoleOwner {
					testUserToken = owner.Token
				} else {
					member := users_testing.CreateTestUser(users_enums.UserRoleMember)
					workspaces_testing.AddMemberToWorkspace(
						workspace,
						member,
						*tt.workspaceRole,
						owner.Token,
						router,
					)
					testUserToken = member.Token
				}
			} else {
				nonMember := users_testing.CreateTestUser(users_enums.UserRoleMember)
				testUserToken = nonMember.Token
			}

			testResp := test_utils.MakePostRequest(
				t,
				router,
				fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
				"Bearer "+testUserToken,
				nil,
				tt.expectedStatusCode,
			)

			if tt.expectSuccess {
				var response backups_download.GenerateDownloadTokenResponse
				err := json.Unmarshal(testResp.Body, &response)
				assert.NoError(t, err)
				assert.NotEmpty(t, response.Token)
				assert.NotEmpty(t, response.Filename)
				assert.Equal(t, backup.ID, response.BackupID)
			} else {
				assert.Contains(t, string(testResp.Body), "insufficient permissions")
			}

			// Cleanup
			databases.RemoveTestDatabase(database)
			time.Sleep(50 * time.Millisecond)
			storages.RemoveTestStorage(storage.ID)
			workspaces_testing.RemoveTestWorkspace(workspace, router)
		})
	}
}

func Test_DownloadBackup_WithValidToken_Success(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Generate download token
	var tokenResponse backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&tokenResponse,
	)

	// Download with token
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), tokenResponse.Token),
		"",
		http.StatusOK,
	)

	// Verify response
	contentDisposition := testResp.Headers.Get("Content-Disposition")
	assert.Contains(t, contentDisposition, "attachment")
	assert.Contains(t, contentDisposition, tokenResponse.Filename)

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_WithoutToken_Unauthorized(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Try to download without token
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file", backup.ID.String()),
		"",
		http.StatusUnauthorized,
	)

	assert.Contains(t, string(testResp.Body), "download token is required")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_WithInvalidToken_Unauthorized(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Try to download with invalid token
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), "invalid-token-xyz"),
		"",
		http.StatusUnauthorized,
	)

	assert.Contains(t, string(testResp.Body), "invalid or expired download token")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_WithExpiredToken_Unauthorized(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Get user for token generation
	userService := users_services.GetUserService()
	user, err := userService.GetUserFromToken(owner.Token)
	assert.NoError(t, err)

	// Create an expired token directly in the database
	expiredToken := createExpiredDownloadToken(backup.ID, user.ID)

	// Try to download with expired token
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), expiredToken),
		"",
		http.StatusUnauthorized,
	)

	assert.Contains(t, string(testResp.Body), "invalid or expired download token")

	// Verify audit log was NOT created for failed download
	time.Sleep(100 * time.Millisecond)
	auditLogService := audit_logs.GetAuditLogService()
	auditLogs, err := auditLogService.GetWorkspaceAuditLogs(
		workspace.ID,
		&audit_logs.GetAuditLogsRequest{
			Limit:  100,
			Offset: 0,
		},
	)
	assert.NoError(t, err)

	found := false
	for _, log := range auditLogs.AuditLogs {
		if strings.Contains(log.Message, "Backup file downloaded") &&
			strings.Contains(log.Message, database.Name) {
			found = true
			break
		}
	}
	assert.False(t, found, "Audit log should NOT be created for failed download with expired token")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_TokenUsedOnce_CannotReuseToken(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Generate download token
	var tokenResponse backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&tokenResponse,
	)

	// Download with token (first time - should succeed)
	test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), tokenResponse.Token),
		"",
		http.StatusOK,
	)

	// Try to download again with same token (should fail)
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), tokenResponse.Token),
		"",
		http.StatusUnauthorized,
	)

	assert.Contains(t, string(testResp.Body), "invalid or expired download token")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_WithDifferentBackupToken_Unauthorized(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database1 := createTestDatabase("Database 1", workspace.ID, owner.Token, router)
	storage := createTestStorage(workspace.ID)

	configService := backups_config.GetBackupConfigService()
	config1, err := configService.GetBackupConfigByDbId(database1.ID)
	assert.NoError(t, err)
	config1.IsBackupsEnabled = true
	config1.StorageID = &storage.ID
	config1.Storage = storage
	_, err = configService.SaveBackupConfig(config1)
	assert.NoError(t, err)

	backup1 := createTestBackup(database1, owner)

	database2 := createTestDatabase("Database 2", workspace.ID, owner.Token, router)
	config2, err := configService.GetBackupConfigByDbId(database2.ID)
	assert.NoError(t, err)
	config2.IsBackupsEnabled = true
	config2.StorageID = &storage.ID
	config2.Storage = storage
	_, err = configService.SaveBackupConfig(config2)
	assert.NoError(t, err)

	backup2 := createTestBackup(database2, owner)

	// Generate token for backup1
	var tokenResponse backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup1.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&tokenResponse,
	)

	// Try to use backup1's token to download backup2 (should fail)
	testResp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup2.ID.String(), tokenResponse.Token),
		"",
		http.StatusUnauthorized,
	)

	assert.Contains(t, string(testResp.Body), "invalid or expired download token")

	// Cleanup
	databases.RemoveTestDatabase(database1)
	databases.RemoveTestDatabase(database2)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_AuditLogWritten(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	// Generate download token
	var tokenResponse backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&tokenResponse,
	)

	// Download with token
	test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), tokenResponse.Token),
		"",
		http.StatusOK,
	)

	time.Sleep(100 * time.Millisecond)

	auditLogService := audit_logs.GetAuditLogService()
	auditLogs, err := auditLogService.GetWorkspaceAuditLogs(
		workspace.ID,
		&audit_logs.GetAuditLogsRequest{
			Limit:  100,
			Offset: 0,
		},
	)
	assert.NoError(t, err)

	found := false
	for _, log := range auditLogs.AuditLogs {
		if strings.Contains(log.Message, "Backup file downloaded") &&
			strings.Contains(log.Message, database.Name) {
			found = true
			break
		}
	}
	assert.True(t, found, "Audit log for backup download not found")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_DownloadBackup_ProperFilenameForPostgreSQL(t *testing.T) {
	tests := []struct {
		name           string
		databaseName   string
		expectedExt    string
		expectedInName string
	}{
		{
			name:           "PostgreSQL database",
			databaseName:   "my_postgres_db",
			expectedExt:    ".dump",
			expectedInName: "my_postgres_db_backup_",
		},
		{
			name:           "Database name with spaces",
			databaseName:   "my test db",
			expectedExt:    ".dump",
			expectedInName: "my_test_db_backup_",
		},
		{
			name:           "Database name with special characters",
			databaseName:   "my:db/test",
			expectedExt:    ".dump",
			expectedInName: "my-db-test_backup_",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			router := createTestRouter()
			owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
			workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

			database := createTestDatabase(tt.databaseName, workspace.ID, owner.Token, router)
			storage := createTestStorage(workspace.ID)

			configService := backups_config.GetBackupConfigService()
			config, err := configService.GetBackupConfigByDbId(database.ID)
			assert.NoError(t, err)

			config.IsBackupsEnabled = true
			config.StorageID = &storage.ID
			config.Storage = storage
			_, err = configService.SaveBackupConfig(config)
			assert.NoError(t, err)

			backup := createTestBackup(database, owner)

			// Generate download token
			var tokenResponse backups_download.GenerateDownloadTokenResponse
			test_utils.MakePostRequestAndUnmarshal(
				t,
				router,
				fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
				"Bearer "+owner.Token,
				nil,
				http.StatusOK,
				&tokenResponse,
			)

			// Download with token
			resp := test_utils.MakeGetRequest(
				t,
				router,
				fmt.Sprintf(
					"/api/v1/backups/%s/file?token=%s",
					backup.ID.String(),
					tokenResponse.Token,
				),
				"",
				http.StatusOK,
			)

			contentDisposition := resp.Headers.Get("Content-Disposition")
			assert.NotEmpty(t, contentDisposition, "Content-Disposition header should be present")

			// Verify the filename contains expected parts
			assert.Contains(
				t,
				contentDisposition,
				tt.expectedInName,
				"Filename should contain sanitized database name",
			)
			assert.Contains(
				t,
				contentDisposition,
				tt.expectedExt,
				"Filename should have correct extension",
			)
			assert.Contains(t, contentDisposition, "attachment", "Should be an attachment")

			// Verify timestamp format (YYYY-MM-DD_HH-mm-ss)
			assert.Regexp(
				t,
				`\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}`,
				contentDisposition,
				"Filename should contain timestamp",
			)

			// Cleanup
			databases.RemoveTestDatabase(database)
			time.Sleep(50 * time.Millisecond)
			storages.RemoveTestStorage(storage.ID)
			workspaces_testing.RemoveTestWorkspace(workspace, router)
		})
	}
}

func Test_SanitizeFilename(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{input: "simple_name", expected: "simple_name"},
		{input: "name with spaces", expected: "name_with_spaces"},
		{input: "name/with\\slashes", expected: "name-with-slashes"},
		{input: "name:with*special?chars", expected: "name-with-special-chars"},
		{input: "name<with>pipes|", expected: "name-with-pipes-"},
		{input: `name"with"quotes`, expected: "name-with-quotes"},
	}

	for _, tt := range tests {
		t.Run(tt.input, func(t *testing.T) {
			result := sanitizeFilename(tt.input)
			assert.Equal(t, tt.expected, result)
		})
	}
}

func Test_CancelBackup_InProgressBackup_SuccessfullyCancelled(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)
	database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)
	storage := createTestStorage(workspace.ID)

	configService := backups_config.GetBackupConfigService()
	config, err := configService.GetBackupConfigByDbId(database.ID)
	assert.NoError(t, err)

	config.IsBackupsEnabled = true
	config.StorageID = &storage.ID
	config.Storage = storage
	_, err = configService.SaveBackupConfig(config)
	assert.NoError(t, err)

	backup := &backups_core.Backup{
		ID:               uuid.New(),
		DatabaseID:       database.ID,
		StorageID:        storage.ID,
		Status:           backups_core.BackupStatusInProgress,
		BackupSizeMb:     0,
		BackupDurationMs: 0,
		CreatedAt:        time.Now().UTC(),
	}

	repo := &backups_core.BackupRepository{}
	err = repo.Save(backup)
	assert.NoError(t, err)

	// Register a cancellable context for the backup
	GetBackupService().taskCancelManager.RegisterTask(backup.ID, func() {})

	resp := test_utils.MakePostRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/cancel", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusNoContent,
	)

	assert.Equal(t, http.StatusNoContent, resp.StatusCode)

	// Verify audit log was created
	admin := users_testing.CreateTestUser(users_enums.UserRoleAdmin)
	userService := users_services.GetUserService()
	adminUser, err := userService.GetUserFromToken(admin.Token)
	assert.NoError(t, err)

	auditLogService := audit_logs.GetAuditLogService()
	auditLogs, err := auditLogService.GetGlobalAuditLogs(
		adminUser,
		&audit_logs.GetAuditLogsRequest{Limit: 100, Offset: 0},
	)
	assert.NoError(t, err)

	foundCancelLog := false
	for _, log := range auditLogs.AuditLogs {
		if strings.Contains(log.Message, "Backup cancelled") &&
			strings.Contains(log.Message, database.Name) {
			foundCancelLog = true
			break
		}
	}
	assert.True(t, foundCancelLog, "Cancel audit log should be created")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_ConcurrentDownloadPrevention(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	var token1Response backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&token1Response,
	)

	var token2Response backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&token2Response,
	)

	downloadInProgress := make(chan bool, 1)
	downloadComplete := make(chan bool, 1)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf(
				"/api/v1/backups/%s/file?token=%s",
				backup.ID.String(),
				token1Response.Token,
			),
			"",
			http.StatusOK,
		)
		downloadComplete <- true
	}()

	time.Sleep(50 * time.Millisecond)

	service := GetBackupService()
	if !service.IsDownloadInProgress(owner.UserID) {
		t.Log("Warning: First download completed before we could test concurrency")
		<-downloadComplete

		// Cleanup before early return
		databases.RemoveTestDatabase(database)
		time.Sleep(50 * time.Millisecond)
		storages.RemoveTestStorage(storage.ID)
		workspaces_testing.RemoveTestWorkspace(workspace, router)
		return
	}

	downloadInProgress <- true

	resp := test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), token2Response.Token),
		"",
		http.StatusConflict,
	)

	var errorResponse map[string]string
	err := json.Unmarshal(resp.Body, &errorResponse)
	assert.NoError(t, err)
	assert.Contains(t, errorResponse["error"], "download already in progress")

	<-downloadComplete
	<-downloadInProgress

	time.Sleep(100 * time.Millisecond)

	var token3Response backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&token3Response,
	)

	test_utils.MakeGetRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), token3Response.Token),
		"",
		http.StatusOK,
	)

	t.Log("Database:", database.Name)
	t.Log(
		"Successfully prevented concurrent downloads and allowed subsequent downloads after completion",
	)

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_GenerateDownloadToken_BlockedWhenDownloadInProgress(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	var token1Response backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&token1Response,
	)

	downloadComplete := make(chan bool, 1)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf(
				"/api/v1/backups/%s/file?token=%s",
				backup.ID.String(),
				token1Response.Token,
			),
			"",
			http.StatusOK,
		)
		downloadComplete <- true
	}()

	time.Sleep(50 * time.Millisecond)

	service := GetBackupService()
	if !service.IsDownloadInProgress(owner.UserID) {
		t.Log("Warning: First download completed before we could test token generation blocking")
		<-downloadComplete

		// Cleanup before early return
		databases.RemoveTestDatabase(database)
		time.Sleep(50 * time.Millisecond)
		storages.RemoveTestStorage(storage.ID)
		workspaces_testing.RemoveTestWorkspace(workspace, router)
		return
	}

	resp := test_utils.MakePostRequest(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusConflict,
	)

	var errorResponse map[string]string
	err := json.Unmarshal(resp.Body, &errorResponse)
	assert.NoError(t, err)
	assert.Contains(t, errorResponse["error"], "download already in progress")

	<-downloadComplete

	time.Sleep(100 * time.Millisecond)

	var token2Response backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&token2Response,
	)

	assert.NotEmpty(t, token2Response.Token)
	assert.NotEqual(t, token1Response.Token, token2Response.Token)

	t.Log("Database:", database.Name)
	t.Log(
		"Successfully blocked token generation during download and allowed generation after completion",
	)

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func createTestRouter() *gin.Engine {
	return CreateTestRouter()
}

func createTestDatabase(
	name string,
	workspaceID uuid.UUID,
	token string,
	router *gin.Engine,
) *databases.Database {
	env := config.GetEnv()
	port, err := strconv.Atoi(env.TestPostgres16Port)
	if err != nil {
		panic(fmt.Sprintf("Failed to parse TEST_POSTGRES_16_PORT: %v", err))
	}

	testDbName := "testdb"
	request := databases.Database{
		Name:        name,
		WorkspaceID: &workspaceID,
		Type:        databases.DatabaseTypePostgres,
		Postgresql: &postgresql.PostgresqlDatabase{
			Version:  tools.PostgresqlVersion16,
			Host:     config.GetEnv().TestLocalhost,
			Port:     port,
			Username: "testuser",
			Password: "testpassword",
			Database: &testDbName,
			CpuCount: 1,
		},
	}

	w := workspaces_testing.MakeAPIRequest(
		router,
		"POST",
		"/api/v1/databases/create",
		"Bearer "+token,
		request,
	)

	if w.Code != http.StatusCreated {
		panic(
			fmt.Sprintf("Failed to create database. Status: %d, Body: %s", w.Code, w.Body.String()),
		)
	}

	var database databases.Database
	if err := json.Unmarshal(w.Body.Bytes(), &database); err != nil {
		panic(err)
	}

	return &database
}

func createTestStorage(workspaceID uuid.UUID) *storages.Storage {
	storage := &storages.Storage{
		WorkspaceID:  workspaceID,
		Type:         storages.StorageTypeLocal,
		Name:         "Test Storage " + uuid.New().String(),
		LocalStorage: &local_storage.LocalStorage{},
	}

	repo := &storages.StorageRepository{}
	storage, err := repo.Save(storage)
	if err != nil {
		panic(err)
	}

	return storage
}

func enableBackupForDatabase(databaseID uuid.UUID) {
	configService := backups_config.GetBackupConfigService()
	config, err := configService.GetBackupConfigByDbId(databaseID)
	if err != nil {
		panic(err)
	}

	config.IsBackupsEnabled = true
	_, err = configService.SaveBackupConfig(config)
	if err != nil {
		panic(err)
	}
}

func createTestDatabaseWithBackups(
	workspace *workspaces_models.Workspace,
	owner *users_dto.SignInResponseDTO,
	router *gin.Engine,
) (*databases.Database, *backups_core.Backup, *storages.Storage) {
	database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)
	storage := createTestStorage(workspace.ID)

	configService := backups_config.GetBackupConfigService()
	config, err := configService.GetBackupConfigByDbId(database.ID)
	if err != nil {
		panic(err)
	}

	config.IsBackupsEnabled = true
	config.StorageID = &storage.ID
	config.Storage = storage
	_, err = configService.SaveBackupConfig(config)
	if err != nil {
		panic(err)
	}

	backup := createTestBackup(database, owner)

	return database, backup, storage
}

func createTestBackup(
	database *databases.Database,
	owner *users_dto.SignInResponseDTO,
) *backups_core.Backup {
	userService := users_services.GetUserService()
	user, err := userService.GetUserFromToken(owner.Token)
	if err != nil {
		panic(err)
	}

	storages, err := storages.GetStorageService().GetStorages(user, *database.WorkspaceID)
	if err != nil || len(storages) == 0 {
		panic("No storage found for workspace")
	}

	backup := &backups_core.Backup{
		ID:               uuid.New(),
		DatabaseID:       database.ID,
		StorageID:        storages[0].ID,
		Status:           backups_core.BackupStatusCompleted,
		BackupSizeMb:     10.5,
		BackupDurationMs: 1000,
		CreatedAt:        time.Now().UTC(),
	}

	repo := &backups_core.BackupRepository{}
	if err := repo.Save(backup); err != nil {
		panic(err)
	}

	// Create a dummy backup file for testing download functionality
	dummyContent := []byte("dummy backup content for testing")
	reader := strings.NewReader(string(dummyContent))
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))
	if err := storages[0].SaveFile(
		context.Background(),
		encryption.GetFieldEncryptor(),
		logger,
		backup.ID,
		reader,
	); err != nil {
		panic(fmt.Sprintf("Failed to create test backup file: %v", err))
	}

	return backup
}

func createExpiredDownloadToken(backupID, userID uuid.UUID) string {
	tokenService := GetBackupService().downloadTokenService
	token, err := tokenService.Generate(backupID, userID)
	if err != nil {
		panic(fmt.Sprintf("Failed to generate download token: %v", err))
	}

	// Manually update the token to be expired
	repo := &backups_download.DownloadTokenRepository{}
	downloadToken, err := repo.FindByToken(token)
	if err != nil || downloadToken == nil {
		panic(fmt.Sprintf("Failed to find generated token: %v", err))
	}

	// Set expiration to 10 minutes ago
	downloadToken.ExpiresAt = time.Now().UTC().Add(-10 * time.Minute)
	if err := repo.Update(downloadToken); err != nil {
		panic(fmt.Sprintf("Failed to update token expiration: %v", err))
	}

	return token
}

func Test_BandwidthThrottling_SingleDownload_Uses75Percent(t *testing.T) {
	router := createTestRouter()
	owner := users_testing.CreateTestUser(users_enums.UserRoleMember)
	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)

	database, backup, storage := createTestDatabaseWithBackups(workspace, owner, router)

	bandwidthManager := backups_download.GetBandwidthManager()
	initialCount := bandwidthManager.GetActiveDownloadCount()

	var tokenResponse backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),
		"Bearer "+owner.Token,
		nil,
		http.StatusOK,
		&tokenResponse,
	)

	downloadStarted := make(chan bool, 1)
	downloadComplete := make(chan bool, 1)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf(
				"/api/v1/backups/%s/file?token=%s",
				backup.ID.String(),
				tokenResponse.Token,
			),
			"",
			http.StatusOK,
		)
		downloadComplete <- true
	}()

	time.Sleep(50 * time.Millisecond)

	activeCount := bandwidthManager.GetActiveDownloadCount()
	if activeCount > initialCount {
		downloadStarted <- true
		assert.Equal(t, initialCount+1, activeCount, "Should have one active download")
	}

	<-downloadComplete
	if len(downloadStarted) > 0 {
		<-downloadStarted
	}

	time.Sleep(50 * time.Millisecond)
	finalCount := bandwidthManager.GetActiveDownloadCount()
	assert.Equal(t, initialCount, finalCount, "Download should be unregistered after completion")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_BandwidthThrottling_MultipleDownloads_ShareBandwidth(t *testing.T) {
	router := createTestRouter()
	owner1 := users_testing.CreateTestUser(users_enums.UserRoleMember)
	owner2 := users_testing.CreateTestUser(users_enums.UserRoleMember)
	owner3 := users_testing.CreateTestUser(users_enums.UserRoleMember)

	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner1, router)
	workspaces_testing.AddMemberToWorkspace(
		workspace,
		owner2,
		users_enums.WorkspaceRoleMember,
		owner1.Token,
		router,
	)
	workspaces_testing.AddMemberToWorkspace(
		workspace,
		owner3,
		users_enums.WorkspaceRoleMember,
		owner1.Token,
		router,
	)

	database := createTestDatabase("Test Database", workspace.ID, owner1.Token, router)
	storage := createTestStorage(workspace.ID)

	configService := backups_config.GetBackupConfigService()
	config, err := configService.GetBackupConfigByDbId(database.ID)
	assert.NoError(t, err)

	config.IsBackupsEnabled = true
	config.StorageID = &storage.ID
	config.Storage = storage
	_, err = configService.SaveBackupConfig(config)
	assert.NoError(t, err)

	backup1 := createTestBackup(database, owner1)
	backup2 := createTestBackup(database, owner2)
	backup3 := createTestBackup(database, owner3)

	var token1, token2, token3 backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup1.ID.String()),
		"Bearer "+owner1.Token,
		nil,
		http.StatusOK,
		&token1,
	)
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup2.ID.String()),
		"Bearer "+owner2.Token,
		nil,
		http.StatusOK,
		&token2,
	)
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup3.ID.String()),
		"Bearer "+owner3.Token,
		nil,
		http.StatusOK,
		&token3,
	)

	bandwidthManager := backups_download.GetBandwidthManager()
	initialCount := bandwidthManager.GetActiveDownloadCount()

	complete1 := make(chan bool, 1)
	complete2 := make(chan bool, 1)
	complete3 := make(chan bool, 1)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup1.ID.String(), token1.Token),
			"",
			http.StatusOK,
		)
		complete1 <- true
	}()

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup2.ID.String(), token2.Token),
			"",
			http.StatusOK,
		)
		complete2 <- true
	}()

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup3.ID.String(), token3.Token),
			"",
			http.StatusOK,
		)
		complete3 <- true
	}()

	time.Sleep(100 * time.Millisecond)

	<-complete1
	<-complete2
	<-complete3

	time.Sleep(100 * time.Millisecond)
	finalCount := bandwidthManager.GetActiveDownloadCount()
	assert.Equal(t, initialCount, finalCount, "All downloads should be unregistered")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}

func Test_BandwidthThrottling_DynamicAdjustment(t *testing.T) {
	router := createTestRouter()
	owner1 := users_testing.CreateTestUser(users_enums.UserRoleMember)
	owner2 := users_testing.CreateTestUser(users_enums.UserRoleMember)

	workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner1, router)
	workspaces_testing.AddMemberToWorkspace(
		workspace,
		owner2,
		users_enums.WorkspaceRoleMember,
		owner1.Token,
		router,
	)

	database := createTestDatabase("Test Database", workspace.ID, owner1.Token, router)
	storage := createTestStorage(workspace.ID)

	configService := backups_config.GetBackupConfigService()
	config, err := configService.GetBackupConfigByDbId(database.ID)
	assert.NoError(t, err)

	config.IsBackupsEnabled = true
	config.StorageID = &storage.ID
	config.Storage = storage
	_, err = configService.SaveBackupConfig(config)
	assert.NoError(t, err)

	backup1 := createTestBackup(database, owner1)
	backup2 := createTestBackup(database, owner2)

	var token1, token2 backups_download.GenerateDownloadTokenResponse
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup1.ID.String()),
		"Bearer "+owner1.Token,
		nil,
		http.StatusOK,
		&token1,
	)
	test_utils.MakePostRequestAndUnmarshal(
		t,
		router,
		fmt.Sprintf("/api/v1/backups/%s/download-token", backup2.ID.String()),
		"Bearer "+owner2.Token,
		nil,
		http.StatusOK,
		&token2,
	)

	bandwidthManager := backups_download.GetBandwidthManager()
	initialCount := bandwidthManager.GetActiveDownloadCount()

	complete1 := make(chan bool, 1)
	complete2 := make(chan bool, 1)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup1.ID.String(), token1.Token),
			"",
			http.StatusOK,
		)
		complete1 <- true
	}()

	time.Sleep(50 * time.Millisecond)

	go func() {
		test_utils.MakeGetRequest(
			t,
			router,
			fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup2.ID.String(), token2.Token),
			"",
			http.StatusOK,
		)
		complete2 <- true
	}()

	<-complete1
	<-complete2

	time.Sleep(100 * time.Millisecond)
	finalCount := bandwidthManager.GetActiveDownloadCount()
	assert.Equal(t, initialCount, finalCount, "All downloads completed and unregistered")

	// Cleanup
	databases.RemoveTestDatabase(database)
	time.Sleep(50 * time.Millisecond)
	storages.RemoveTestStorage(storage.ID)
	workspaces_testing.RemoveTestWorkspace(workspace, router)
}
