import type { User } from '@n8n/db';
import { mock } from 'jest-mock-extended';
import { simpleGit } from 'simple-git';
import type { SimpleGit } from 'simple-git';

import { SourceControlGitService } from '../source-control-git.service.ee';
import type { SourceControlPreferencesService } from '../source-control-preferences.service.ee';
import type { SourceControlPreferences } from '../types/source-control-preferences';

const MOCK_BRANCHES = {
	all: ['origin/master', 'origin/feature/branch'],
	branches: {
		'origin/master': {},
		'origin/feature/branch': {},
	},
	current: 'master',
};

const mockGitInstance = {
	branch: jest.fn().mockResolvedValue(MOCK_BRANCHES),
	env: jest.fn().mockReturnThis(),
};

jest.mock('simple-git', () => {
	return {
		simpleGit: jest.fn().mockImplementation(() => mockGitInstance),
	};
});

describe('SourceControlGitService', () => {
	const mockSourceControlPreferencesService = mock<SourceControlPreferencesService>();
	const sourceControlGitService = new SourceControlGitService(
		mock(),
		mock(),
		mockSourceControlPreferencesService,
	);

	beforeEach(() => {
		sourceControlGitService.git = simpleGit();
	});

	describe('getBranches', () => {
		it('should support branch names containing slashes', async () => {
			const branches = await sourceControlGitService.getBranches();
			expect(branches.branches).toEqual(['master', 'feature/branch']);
		});
	});

	describe('initRepository', () => {
		describe('when local repo is set up after remote is ready', () => {
			it('should track remote', async () => {
				/**
				 * Arrange
				 */
				const gitService = new SourceControlGitService(mock(), mock(), mock());
				const prefs = mock<SourceControlPreferences>({ branchName: 'main' });
				const user = mock<User>();
				const git = mock<SimpleGit>();
				const checkoutSpy = jest.spyOn(git, 'checkout');
				const branchSpy = jest.spyOn(git, 'branch');
				gitService.git = git;
				jest.spyOn(gitService, 'setGitCommand').mockResolvedValue();
				jest
					.spyOn(gitService, 'getBranches')
					.mockResolvedValue({ currentBranch: '', branches: ['main'] });

				/**
				 * Act
				 */
				await gitService.initRepository(prefs, user);

				/**
				 * Assert
				 */
				expect(checkoutSpy).toHaveBeenCalledWith('main');
				expect(branchSpy).toHaveBeenCalledWith(['--set-upstream-to=origin/main', 'main']);
			});
		});

		describe('when fetch fails during remote tracking setup', () => {
			it('should log warning and not throw when tracking fetch failures are tolerated', async () => {
				const mockLogger = mock<any>();
				const gitService = new SourceControlGitService(mockLogger, mock(), mock());
				const prefs = mock<SourceControlPreferences>({ branchName: 'main' });
				const user = mock<User>();
				const git = mock<SimpleGit>();
				gitService.git = git;
				jest.spyOn(gitService, 'setGitCommand').mockResolvedValue();

				const fetchError = new Error('Authentication failed for HTTPS remote');
				jest.spyOn(gitService, 'fetch').mockRejectedValue(fetchError);

				await gitService.initRepository(prefs, user, {
					tolerateTrackingFetchFailure: true,
				});

				expect(mockLogger.warn).toHaveBeenCalledWith(
					'Failed to fetch during remote tracking setup',
					{ error: fetchError },
				);
			});

			it('should throw when tracking fetch failures are NOT tolerated', async () => {
				const gitService = new SourceControlGitService(mock(), mock(), mock());
				const prefs = mock<SourceControlPreferences>({ branchName: 'main' });
				const user = mock<User>();
				const git = mock<SimpleGit>();
				gitService.git = git;
				jest.spyOn(gitService, 'setGitCommand').mockResolvedValue();

				const fetchError = new Error('Authentication failed for HTTPS remote');
				jest.spyOn(gitService, 'fetch').mockRejectedValue(fetchError);

				await expect(
					gitService.initRepository(prefs, user, {
						tolerateTrackingFetchFailure: false,
					}),
				).rejects.toThrow(fetchError);
			});
		});

		describe('repository URL authorization', () => {
			it('should set repositoryUrl URL for SSH connection type', async () => {
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);
				const originUrl = 'git@github.com:user/repo.git';
				const prefs = mock<SourceControlPreferences>({
					repositoryUrl: originUrl,
					connectionType: 'ssh',
					branchName: 'main',
				});
				const user = mock<User>();
				const git = mock<SimpleGit>();
				const addRemoteSpy = jest.spyOn(git, 'addRemote');
				jest.spyOn(gitService, 'setGitUserDetails').mockResolvedValue();
				// Mock getBranches and fetch to avoid remote tracking logic
				jest
					.spyOn(gitService, 'getBranches')
					.mockResolvedValue({ currentBranch: 'main', branches: [] });
				jest.spyOn(gitService, 'fetch').mockResolvedValue({} as any);
				gitService.git = git;

				await gitService.initRepository(prefs, user);

				expect(addRemoteSpy).toHaveBeenCalledWith('origin', originUrl);
				expect(mockPreferencesService.getDecryptedHttpsCredentials).not.toHaveBeenCalled();
			});

			it('should set repositoryUrl URL for HTTPS connection type', async () => {
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const credentials = { username: 'testuser', password: 'test:pass#word' };
				mockPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(credentials);

				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);
				const originUrl = 'https://github.com/user/repo.git';
				const prefs = mock<SourceControlPreferences>({
					repositoryUrl: originUrl,
					connectionType: 'https',
					branchName: 'main',
				});
				const user = mock<User>();
				const git = mock<SimpleGit>();
				const addRemoteSpy = jest.spyOn(git, 'addRemote');
				jest.spyOn(gitService, 'setGitUserDetails').mockResolvedValue();
				// Mock getBranches and fetch to avoid remote tracking logic
				jest
					.spyOn(gitService, 'getBranches')
					.mockResolvedValue({ currentBranch: 'main', branches: [] });
				jest.spyOn(gitService, 'fetch').mockResolvedValue({} as any);
				gitService.git = git;

				await gitService.initRepository(prefs, user);

				expect(addRemoteSpy).toHaveBeenCalledWith('origin', originUrl);
			});

			it('should throw error when HTTPS connection type is specified but no credentials found', async () => {
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const errorMessage = 'Error';
				mockPreferencesService.getDecryptedHttpsCredentials.mockRejectedValue(
					new Error(errorMessage),
				);
				mockPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'https',
					repositoryUrl: 'https://github.com/user/repo.git',
				} as never);

				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);
				const prefs = mock<SourceControlPreferences>({
					repositoryUrl: 'https://github.com/user/repo.git',
					connectionType: 'https',
					branchName: 'main',
				});
				const user = mock<User>();
				const git = mock<SimpleGit>();
				gitService.git = git;

				await expect(gitService.initRepository(prefs, user)).rejects.toThrow(errorMessage);
				expect(mockPreferencesService.getDecryptedHttpsCredentials).toHaveBeenCalled();
			});
		});
	});

	describe('ensureBranchSetup', () => {
		describe('when current branch matches target branch', () => {
			it('should not modify anything', async () => {
				const gitService = new SourceControlGitService(mock(), mock(), mock());
				const git = mock<SimpleGit>();
				git.branch.mockResolvedValue({ current: 'main' } as never);
				gitService.git = git;

				const fetchSpy = jest.spyOn(gitService, 'fetch');
				const checkoutSpy = jest.spyOn(git, 'checkout');

				// Call private method using type assertion
				await (gitService as any).ensureBranchSetup('main');

				expect(fetchSpy).not.toHaveBeenCalled();
				expect(checkoutSpy).not.toHaveBeenCalled();
			});
		});

		describe('when current branch does not match target branch', () => {
			it('should checkout and track the target branch from remote', async () => {
				const gitService = new SourceControlGitService(mock(), mock(), mock());
				const git = mock<SimpleGit>();
				git.branch.mockResolvedValue({ current: 'master' } as never);
				gitService.git = git;

				jest.spyOn(gitService, 'fetch').mockResolvedValue({} as never);
				jest.spyOn(gitService, 'getBranches').mockResolvedValue({
					currentBranch: 'master',
					branches: ['main', 'develop'],
				});

				await (gitService as any).ensureBranchSetup('main');

				expect(git.checkout).toHaveBeenCalledWith('main');
				expect(git.branch).toHaveBeenCalledWith(['--set-upstream-to=origin/main', 'main']);
			});

			it('should not checkout if target branch does not exist on remote', async () => {
				const gitService = new SourceControlGitService(mock(), mock(), mock());
				const git = mock<SimpleGit>();
				git.branch.mockResolvedValue({ current: 'master' } as never);
				gitService.git = git;

				jest.spyOn(gitService, 'fetch').mockResolvedValue({} as never);
				jest.spyOn(gitService, 'getBranches').mockResolvedValue({
					currentBranch: 'master',
					branches: ['develop', 'feature'],
				});

				await (gitService as any).ensureBranchSetup('main');

				expect(git.checkout).not.toHaveBeenCalled();
			});
		});

		describe('when fetch fails', () => {
			it('should log warning and return without failing', async () => {
				const mockLogger = mock<any>();
				const gitService = new SourceControlGitService(mockLogger, mock(), mock());
				const git = mock<SimpleGit>();
				git.branch.mockResolvedValue({ current: 'master' } as never);
				gitService.git = git;

				const fetchError = new Error('Network error');
				jest.spyOn(gitService, 'fetch').mockRejectedValue(fetchError);

				// Should not throw
				await (gitService as any).ensureBranchSetup('main');

				expect(mockLogger.warn).toHaveBeenCalledWith(
					'Failed to fetch during branch setup recovery',
					{ error: fetchError },
				);
				expect(git.checkout).not.toHaveBeenCalled();
			});
		});

		describe('when checkout fails', () => {
			it('should log warning and not throw', async () => {
				const mockLogger = mock<any>();
				const gitService = new SourceControlGitService(mockLogger, mock(), mock());
				const git = mock<SimpleGit>();
				git.branch.mockResolvedValue({ current: 'master' } as never);
				git.checkout.mockRejectedValue(new Error('Checkout failed'));
				gitService.git = git;

				jest.spyOn(gitService, 'fetch').mockResolvedValue({} as never);
				jest.spyOn(gitService, 'getBranches').mockResolvedValue({
					currentBranch: 'master',
					branches: ['main'],
				});

				// Should not throw
				await (gitService as any).ensureBranchSetup('main');

				expect(mockLogger.warn).toHaveBeenCalledWith(
					'Failed to checkout branch during recovery',
					expect.objectContaining({ targetBranch: 'main' }),
				);
			});
		});
	});

	describe('setGitCommand', () => {
		it('should setup git client for https connection', async () => {
			const credentials = { username: 'testuser', password: 'testpass' };
			mockSourceControlPreferencesService.getPreferences.mockReturnValue({
				connectionType: 'https',
				repositoryUrl: 'https://github.com/user/repo.git',
			} as never);
			mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
				credentials,
			);

			// Clear previous calls to simpleGit
			(simpleGit as jest.Mock).mockClear();

			await sourceControlGitService.setGitCommand();

			expect(mockGitInstance.env).toHaveBeenCalledWith('GIT_TERMINAL_PROMPT', '0');
			const expectedCredentialScript = `!f() { echo username='${credentials.username}'; echo password='${credentials.password}'; }; f`;
			expect(simpleGit).toHaveBeenCalledWith(
				expect.objectContaining({
					binary: 'git',
					maxConcurrentProcesses: 6,
					trimmed: false,
					config: [`credential.helper=${expectedCredentialScript}`, 'credential.useHttpPath=true'],
					unsafe: { allowUnsafeCredentialHelper: true },
				}),
			);
		});

		it('should escape https credentials to prevent command injection', async () => {
			// simulate credentials that would try to inject an rm -rf command by breaking out of the echo command with single quotes inside them
			const credentials = { username: "user'; rm -rf /", password: "pass'; rm -rf /" };

			mockSourceControlPreferencesService.getPreferences.mockReturnValue({
				connectionType: 'https',
				repositoryUrl: 'https://github.com/user/repo.git',
			} as never);
			mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
				credentials,
			);
			// Clear previous calls to simpleGit
			(simpleGit as jest.Mock).mockClear();

			await sourceControlGitService.setGitCommand();

			expect(mockGitInstance.env).toHaveBeenCalledWith('GIT_TERMINAL_PROMPT', '0');
			const expectedCredentialScript =
				"!f() { echo username='user'\"'\"'; rm -rf /'; echo password='pass'\"'\"'; rm -rf /'; }; f";
			expect(simpleGit).toHaveBeenCalledWith(
				expect.objectContaining({
					config: [`credential.helper=${expectedCredentialScript}`, 'credential.useHttpPath=true'],
				}),
			);
		});

		it('should setup git client for ssh connection', async () => {
			// @ts-expect-error required for testing
			mockSourceControlPreferencesService['sshFolder'] = '.ssh';
			mockSourceControlPreferencesService.getPrivateKeyPath.mockResolvedValue('private-key');
			mockSourceControlPreferencesService.getPreferences.mockReturnValue({
				connectionType: 'ssh',
			} as never);
			(simpleGit as jest.Mock).mockClear();

			await sourceControlGitService.setGitCommand();

			expect(simpleGit).toHaveBeenCalledWith(
				expect.objectContaining({
					unsafe: { allowUnsafeSshCommand: true },
				}),
			);
			expect(mockGitInstance.env).toHaveBeenCalledWith(
				'GIT_SSH_COMMAND',
				'ssh -o UserKnownHostsFile=".ssh/known_hosts" -o StrictHostKeyChecking=accept-new -i "private-key"',
			);
			expect(mockGitInstance.env).toHaveBeenCalledWith('GIT_TERMINAL_PROMPT', '0');
		});

		describe('proxy configuration', () => {
			const originalEnv = process.env;

			beforeEach(() => {
				process.env = { ...originalEnv };
				delete process.env.HTTP_PROXY;
				delete process.env.HTTPS_PROXY;
				delete process.env.http_proxy;
				delete process.env.https_proxy;
				delete process.env.NO_PROXY;
				delete process.env.no_proxy;
				delete process.env.ALL_PROXY;
				delete process.env.all_proxy;
				(simpleGit as jest.Mock).mockClear();
			});

			afterEach(() => {
				process.env = originalEnv;
			});

			it('should add http.proxy config when HTTPS_PROXY is set for https repository', async () => {
				const credentials = { username: 'testuser', password: 'testpass' };
				const repositoryUrl = 'https://github.com/user/repo.git';
				const proxyUrl = 'http://proxy.company.com:8080';

				process.env.HTTPS_PROXY = proxyUrl;

				mockSourceControlPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'https',
					repositoryUrl,
				} as never);
				mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
					credentials,
				);

				await sourceControlGitService.setGitCommand();

				// Git uses http.proxy for both HTTP and HTTPS URLs
				const simpleGitCalls = (simpleGit as jest.Mock).mock.calls;
				expect(simpleGitCalls.length).toBeGreaterThan(0);
				const lastCallConfig = simpleGitCalls[simpleGitCalls.length - 1][0].config;
				expect(lastCallConfig).toContain(`http.proxy=${proxyUrl}`);
			});

			it('should add http.proxy config when HTTP_PROXY is set for http repository', async () => {
				const credentials = { username: 'testuser', password: 'testpass' };
				const repositoryUrl = 'http://internal-git.company.com/repo.git';
				const proxyUrl = 'http://proxy.company.com:8080';

				process.env.HTTP_PROXY = proxyUrl;

				mockSourceControlPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'https',
					repositoryUrl,
				} as never);
				mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
					credentials,
				);

				await sourceControlGitService.setGitCommand();

				const simpleGitCalls = (simpleGit as jest.Mock).mock.calls;
				expect(simpleGitCalls.length).toBeGreaterThan(0);
				const lastCallConfig = simpleGitCalls[simpleGitCalls.length - 1][0].config;
				expect(lastCallConfig).toContain(`http.proxy=${proxyUrl}`);
			});

			it('should not add proxy config when no proxy environment variables are set', async () => {
				const credentials = { username: 'testuser', password: 'testpass' };
				const repositoryUrl = 'https://github.com/user/repo.git';

				mockSourceControlPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'https',
					repositoryUrl,
				} as never);
				mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
					credentials,
				);

				await sourceControlGitService.setGitCommand();

				const simpleGitCalls = (simpleGit as jest.Mock).mock.calls;
				expect(simpleGitCalls.length).toBeGreaterThan(0);
				const lastCallConfig = simpleGitCalls[simpleGitCalls.length - 1][0].config as string[];
				const hasProxyConfig = lastCallConfig.some((c: string) => c.includes('proxy='));
				expect(hasProxyConfig).toBe(false);
			});

			it('should respect NO_PROXY and not add proxy config when repository matches', async () => {
				const credentials = { username: 'testuser', password: 'testpass' };
				const repositoryUrl = 'https://github.com/user/repo.git';
				const proxyUrl = 'http://proxy.company.com:8080';

				process.env.HTTPS_PROXY = proxyUrl;
				process.env.NO_PROXY = 'github.com';

				mockSourceControlPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'https',
					repositoryUrl,
				} as never);
				mockSourceControlPreferencesService.getDecryptedHttpsCredentials.mockResolvedValue(
					credentials,
				);

				await sourceControlGitService.setGitCommand();

				const simpleGitCalls = (simpleGit as jest.Mock).mock.calls;
				expect(simpleGitCalls.length).toBeGreaterThan(0);
				const lastCallConfig = simpleGitCalls[simpleGitCalls.length - 1][0].config as string[];
				const hasProxyConfig = lastCallConfig.some((c: string) => c.includes('proxy='));
				expect(hasProxyConfig).toBe(false);
			});
		});
	});

	describe('getFileContent', () => {
		it('should return file content at HEAD version', async () => {
			// Arrange
			const filePath = 'workflows/12345.json';
			const expectedContent = '{"id":"12345","name":"Test Workflow"}';
			const git = mock<SimpleGit>();
			const showSpy = jest.spyOn(git, 'show');
			showSpy.mockResolvedValue(expectedContent);
			sourceControlGitService.git = git;

			// Act
			const content = await sourceControlGitService.getFileContent(filePath);

			// Assert
			expect(showSpy).toHaveBeenCalledWith([`HEAD:${filePath}`]);
			expect(content).toBe(expectedContent);
		});

		it('should return file content at specific commit', async () => {
			// Arrange
			const filePath = 'workflows/12345.json';
			const commitHash = 'abc123';
			const expectedContent = '{"id":"12345","name":"Test Workflow"}';
			const git = mock<SimpleGit>();
			const showSpy = jest.spyOn(git, 'show');
			showSpy.mockResolvedValue(expectedContent);
			sourceControlGitService.git = git;

			// Act
			const content = await sourceControlGitService.getFileContent(filePath, commitHash);

			// Assert
			expect(showSpy).toHaveBeenCalledWith([`${commitHash}:${filePath}`]);
			expect(content).toBe(expectedContent);
		});
	});

	describe('path normalization', () => {
		describe('cross-platform path handling', () => {
			beforeEach(() => {
				jest.clearAllMocks();
			});

			it('should normalize Windows paths to POSIX format for SSH command', async () => {
				// Arrange
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const windowsPath = 'C:\\Users\\Test\\.n8n\\ssh_private_key_temp';
				const sshFolder = 'C:\\Users\\Test\\.n8n\\.ssh';

				// Mock the getPrivateKeyPath to return a Windows path
				mockPreferencesService.getPrivateKeyPath.mockResolvedValue(windowsPath);
				// Mock getPreferences to return SSH connection type (required for new functionality)
				mockPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'ssh',
					connected: true,
					repositoryUrl: 'git@github.com:user/repo.git',
					branchName: 'main',
					branchReadOnly: false,
					branchColor: '#5296D6',
					initRepo: false,
					keyGeneratorType: 'ed25519',
				});

				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);

				// Act
				await gitService.setGitCommand('/git/folder', sshFolder);

				// Assert - verify Windows paths are normalized to POSIX format
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('C:/Users/Test/.n8n/ssh_private_key_temp'), // Forward slashes
				);
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('C:/Users/Test/.n8n/.ssh/known_hosts'), // Forward slashes
				);
				// Ensure no backslashes remain in the SSH command
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.not.stringContaining('\\'),
				);
			});

			it('should create properly quoted SSH command', async () => {
				// Arrange
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const privateKeyPath = 'C:/Users/Test User/.n8n/ssh_private_key_temp';
				const sshFolder = 'C:/Users/Test User/.n8n/.ssh';

				// Mock the getPrivateKeyPath to return a path with spaces
				mockPreferencesService.getPrivateKeyPath.mockResolvedValue(privateKeyPath);
				// Mock getPreferences to return SSH connection type
				mockPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'ssh',
					connected: true,
					repositoryUrl: 'git@github.com:user/repo.git',
					branchName: 'main',
					branchReadOnly: false,
					branchColor: '#5296D6',
					initRepo: false,
					keyGeneratorType: 'ed25519',
				});

				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);

				// Act
				await gitService.setGitCommand('/git/folder', sshFolder);

				// Assert - verify paths with spaces are properly quoted
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('"C:/Users/Test User/.n8n/ssh_private_key_temp"'), // Quoted path with spaces
				);
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('"C:/Users/Test User/.n8n/.ssh/known_hosts"'), // Quoted known_hosts path
				);
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('UserKnownHostsFile='),
				);
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('StrictHostKeyChecking=accept-new'),
				);
			});

			it('should escape double quotes in paths to prevent command injection', async () => {
				// Arrange
				const mockPreferencesService = mock<SourceControlPreferencesService>();
				const pathWithQuotes = 'C:/Users/Test"User/.n8n/ssh_private_key_temp';
				const sshFolder = 'C:/Users/Test"User/.n8n/.ssh';

				// Mock the getPrivateKeyPath to return a path with quotes
				mockPreferencesService.getPrivateKeyPath.mockResolvedValue(pathWithQuotes);
				// Mock getPreferences to return SSH connection type
				mockPreferencesService.getPreferences.mockReturnValue({
					connectionType: 'ssh',
					connected: true,
					repositoryUrl: 'git@github.com:user/repo.git',
					branchName: 'main',
					branchReadOnly: false,
					branchColor: '#5296D6',
					initRepo: false,
					keyGeneratorType: 'ed25519',
				});

				const gitService = new SourceControlGitService(mock(), mock(), mockPreferencesService);

				// Act
				await gitService.setGitCommand('/git/folder', sshFolder);

				// Assert - verify the SSH command was properly escaped
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.stringContaining('Test\\"User'), // Escaped quote
				);
				expect(mockGitInstance.env).toHaveBeenCalledWith(
					'GIT_SSH_COMMAND',
					expect.not.stringContaining('Test"User'), // No unescaped quote in final command
				);
			});
		});
	});
});
