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

const {
  buildHostPayloadFromVm,
  normalizeBaseUrl,
  normalizeVCenterVm,
  vmMatchesFilter
} = await load('../services/vcenterService.js');

test('normalizeBaseUrl trims trailing slashes', () => {
  assert.equal(normalizeBaseUrl('https://vcenter.lab.local///'), 'https://vcenter.lab.local');
});

test('normalizeVCenterVm maps guest identity and networking into a host candidate', () => {
  const candidate = normalizeVCenterVm(
    { vm: 'vm-42', name: 'ENG-ENT-APP01', power_state: 'POWERED_ON' },
    { host_name: 'eng-ent-app01.contoso.local', ip_address: '10.42.1.20', full_name: 'Microsoft Windows Server 2022' },
    [{ ip: { ip_addresses: [{ ip_address: 'fe80::1' }, { ip_address: '10.42.1.21' }] } }]
  );

  assert.equal(candidate.id, 'vm-42');
  assert.equal(candidate.name, 'ENG-ENT-APP01');
  assert.equal(candidate.fqdn, 'eng-ent-app01.contoso.local');
  assert.equal(candidate.address, 'eng-ent-app01.contoso.local');
  assert.deepEqual(candidate.ipAddresses, ['10.42.1.20', '10.42.1.21']);
  assert.equal(candidate.osFamily, 'windows');
});

test('vmMatchesFilter supports hostname contains and IP equals matching', () => {
  const candidate = { name: 'ENG-ENT-APP01', fqdn: 'app01.contoso.local', ipAddress: '10.42.1.20', ipAddresses: ['10.42.1.20'] };

  assert.equal(vmMatchesFilter(candidate, { field: 'hostname', operator: 'contains', value: 'eng-ent' }), true);
  assert.equal(vmMatchesFilter(candidate, { field: 'ip', operator: 'equals', value: '10.42.1.20' }), true);
  assert.equal(vmMatchesFilter(candidate, { field: 'fqdn', operator: 'startsWith', value: 'db' }), false);
});

test('buildHostPayloadFromVm attaches credential, tags, transport, and import notes', () => {
  const payload = buildHostPayloadFromVm(
    {
      id: 'vm-42',
      name: 'ENG-ENT-APP01',
      fqdn: 'eng-ent-app01.contoso.local',
      address: 'eng-ent-app01.contoso.local',
      osFamily: 'windows',
      powerState: 'POWERED_ON',
      guestFullName: 'Microsoft Windows Server 2022',
      ipAddresses: ['10.42.1.20']
    },
    { credentialId: 'cred_1', transport: 'winrm', tags: ['engineering'], visibility: 'group', groupId: 'grp_1' }
  );

  assert.equal(payload.credentialId, 'cred_1');
  assert.equal(payload.transport, 'winrm');
  assert.equal(payload.visibility, 'group');
  assert.equal(payload.groupId, 'grp_1');
  assert.ok(payload.tags.includes('vcenter:vm-42'));
  assert.ok(payload.tags.includes('engineering'));
  assert.match(payload.notes, /Imported from VMware vCenter VM vm-42/);
});
