import { expect, tap } from '@git.zone/tstest/tapbundle';
import { createHomeWizardDiscoveryDescriptor } from '../../ts/integrations/homewizard/index.js';

tap.test('matches HomeWizard zeroconf records from upstream manifest services', async () => {
  const descriptor = createHomeWizardDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homewizard-zeroconf-match');

  const v1 = await matcher!.matches({
    name: 'p1meter-aabbcc._hwenergy._tcp.local.',
    type: '_hwenergy._tcp.local.',
    host: 'p1meter-aabbcc.local',
    port: 80,
    txt: {
      api_enabled: '1',
      path: '/api/v1',
      serial: 'AABBCCDDEEFF',
      product_name: 'P1 Meter',
      product_type: 'HWE-P1',
    },
  }, {});
  const v2 = await matcher!.matches({
    name: 'p1meter-aabbcc._homewizard._tcp.local.',
    type: '_homewizard._tcp.local.',
    host: 'p1meter-aabbcc.local',
    port: 443,
    properties: {
      api_version: '2.2.0',
      id: 'appliance/p1dongle/AABBCCDDEEFF',
      serial: 'AABBCCDDEEFF',
      product_name: 'P1 Meter',
      product_type: 'HWE-P1',
    },
  }, {});

  expect(v1.matched).toBeTrue();
  expect(v1.candidate?.metadata?.apiVersion).toEqual('v1');
  expect(v1.normalizedDeviceId).toEqual('HWE-P1_AABBCCDDEEFF');
  expect(v2.matched).toBeTrue();
  expect(v2.candidate?.metadata?.apiVersion).toEqual('v2');
  expect(v2.candidate?.port).toEqual(443);
});

tap.test('matches HomeWizard DHCP and manual candidates', async () => {
  const descriptor = createHomeWizardDiscoveryDescriptor();
  const dhcpMatcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homewizard-dhcp-match');
  const manualMatcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homewizard-manual-match');
  const validator = descriptor.getValidators()[0];

  const dhcp = await dhcpMatcher!.matches({ hostname: 'p1meter-aabbcc', ip: '192.168.1.50', macaddress: 'aa:bb:cc:dd:ee:ff' }, {});
  const manual = await manualMatcher!.matches({ host: '192.168.1.51', token: 'TOKEN', productType: 'HWE-P1', name: 'P1 Meter' }, {});
  const validation = await validator.validate(manual.candidate!, {});

  expect(dhcp.matched).toBeTrue();
  expect(dhcp.candidate?.source).toEqual('dhcp');
  expect(manual.matched).toBeTrue();
  expect(manual.candidate?.metadata?.token).toEqual('TOKEN');
  expect(validation.matched).toBeTrue();
});

export default tap.start();
