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

tap.test('matches devolo device API mDNS records', async () => {
  const descriptor = createDevoloHomeNetworkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    type: '_dvl-deviceapi._tcp.local.',
    name: 'devolo-office._dvl-deviceapi._tcp.local.',
    host: '192.168.1.20',
    port: 80,
    txt: {
      Product: 'Magic 2 WiFi 6',
      SN: 'S12345',
      MT: '8528',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('devolo_home_network');
  expect(result.normalizedDeviceId).toEqual('S12345');
  expect(result.candidate?.metadata?.MT).toEqual('8528');
});

tap.test('rejects devolo Home Control central units', async () => {
  const descriptor = createDevoloHomeNetworkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    type: '_dvl-deviceapi._tcp.local.',
    host: '192.168.1.21',
    txt: { Product: 'Home Control Central Unit', SN: 'HC1', MT: '2600' },
  }, {});

  expect(result.matched).toBeFalse();
  expect(result.metadata?.homeControl).toBeTrue();
});

tap.test('matches and validates manual snapshot candidates', async () => {
  const descriptor = createDevoloHomeNetworkDiscoveryDescriptor();
  const manualMatcher = descriptor.getMatchers()[1];
  const validator = descriptor.getValidators()[0];
  const manual = await manualMatcher.matches({
    host: '192.168.1.22',
    product: 'devolo Magic 2 LAN',
    serialNumber: 'S67890',
    snapshot: {
      connected: true,
      device: { host: '192.168.1.22', name: 'Basement Adapter', serialNumber: 'S67890' },
      plcDevices: [],
      plcLinks: [],
      wifiStations: [],
      neighboringWifiNetworks: [],
      sensors: {},
      switches: {},
      actions: [],
      events: [],
    },
  }, {});
  const validated = await validator.validate(manual.candidate!, {});

  expect(manual.matched).toBeTrue();
  expect(validated.matched).toBeTrue();
  expect(validated.metadata?.liveHttpImplemented).toEqual(false);
});

export default tap.start();
