import './setup.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { load } from './setup.mjs';

const { buildPackagerInvocation, expectedOutputFile, resolveToolPath, builderAvailability } = await load('../services/intuneWinBuilder.js');
const { isPathInside, normalizePackagePath, sanitizeFileName } = await load('../utils/pathUtils.js');

test('bundled invocation uses IntuneWinAppUtil flags', () => {
  const inv = buildPackagerInvocation({ toolPath: 'C:/tools/IntuneWinAppUtil.exe', sourceFolder: 'C:/src', setupFile: 'setup.exe', outputDir: 'C:/out' });
  assert.equal(inv.shell, false);
  assert.equal(inv.command, 'C:/tools/IntuneWinAppUtil.exe');
  assert.deepEqual(inv.args, ['-c', 'C:/src', '-s', 'setup.exe', '-o', 'C:/out', '-q']);
});

test('external command template substitutes placeholders', () => {
  const inv = buildPackagerInvocation({
    commandTemplate: 'pack --src {source} --setup {setup} --out {output}',
    sourceFolder: '/s', setupFile: 'a.msi', outputDir: '/o'
  });
  assert.equal(inv.shell, true);
  assert.equal(inv.command, 'pack --src /s --setup a.msi --out /o');
});

test('expectedOutputFile names after the setup base name', () => {
  assert.ok(expectedOutputFile('/out', 'ContosoVpnSetup.exe').endsWith('ContosoVpnSetup.intunewin'));
  assert.ok(expectedOutputFile('/out', 'app.msi').endsWith('app.intunewin'));
  assert.ok(expectedOutputFile('/out', 'Files\\Vendor Setup.exe').endsWith('Vendor Setup.intunewin'));
});

test('path utilities normalize Windows-style upload and package paths', () => {
  assert.equal(sanitizeFileName('C:\\temp\\Contoso VPN?.msi'), 'Contoso VPN-.msi');
  assert.equal(normalizePackagePath('Files\\Installers\\..\\setup.exe'), 'Files/Installers/setup.exe');
  assert.equal(normalizePackagePath('../SupportFiles/config.json'), 'SupportFiles/config.json');
});

test('path containment rejects sibling directories with the same prefix', () => {
  assert.equal(isPathInside('/tmp/FileLocker', '/tmp/FileLocker/assets/a.bin'), true);
  assert.equal(isPathInside('/tmp/FileLocker', '/tmp/FileLocker2/assets/a.bin'), false);
});

test('resolveToolPath defaults into the tools directory', () => {
  assert.ok(resolveToolPath().toLowerCase().includes('intunewinapputil.exe'));
});

test('builderAvailability reports unavailable when the tool is missing on this host', () => {
  // The test host has no tool placed and is not Windows, so build is unavailable.
  const availability = builderAvailability();
  assert.equal(availability.available, false);
  assert.ok(availability.reason);
});
