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

tap.test('matches UniFi mDNS, SSDP, manual, and discovery records', async () => {
  const descriptor = createUnifiDiscoveryDescriptor();
  const mdnsMatcher = descriptor.getMatchers()[0];
  const ssdpMatcher = descriptor.getMatchers()[1];
  const manualMatcher = descriptor.getMatchers()[2];
  const discoveryMatcher = descriptor.getMatchers()[3];

  const mdnsResult = await mdnsMatcher.matches({
    type: '_unifi._tcp.local.',
    name: 'UniFi Network._unifi._tcp.local.',
    host: 'unifi.local',
    txt: {
      mac: 'b4fbe4123456',
      model: 'UniFi Dream Machine',
      controller_uuid: 'controller-1',
    },
  }, {});
  const ssdpResult = await ssdpMatcher.matches({
    location: 'https://192.168.1.1:443/description.xml',
    manufacturer: 'Ubiquiti Networks',
    modelDescription: 'UniFi Dream Machine',
    usn: 'uuid:udm-1',
  }, {});
  const manualResult = await manualMatcher.matches({
    host: '192.168.1.2',
    site: 'default',
    model: 'UniFi Network',
  }, {});
  const discoveryResult = await discoveryMatcher.matches({
    source_ip: '192.168.1.1',
    hw_addr: 'B4:FB:E4:12:34:56',
    services: { network: true },
  }, {});

  expect(mdnsResult.matched).toBeTrue();
  expect(mdnsResult.normalizedDeviceId).toEqual('controller-1');
  expect(ssdpResult.matched).toBeTrue();
  expect(ssdpResult.candidate?.host).toEqual('192.168.1.1');
  expect(manualResult.matched).toBeTrue();
  expect(manualResult.candidate?.port).toEqual(443);
  expect(discoveryResult.normalizedDeviceId).toEqual('b4:fb:e4:12:34:56');
});

tap.test('validates UniFi candidates', async () => {
  const validator = createUnifiDiscoveryDescriptor().getValidators()[0];
  const result = await validator.validate({
    source: 'ssdp',
    host: '192.168.1.1',
    manufacturer: 'Ubiquiti Networks',
    model: 'UniFi Dream Machine SE',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('high');
});

export default tap.start();
