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

tap.test('matches TP-Link Kasa/Tapo mDNS records', async () => {
  const descriptor = createTplinkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    type: '_tplink._tcp.local.',
    name: 'Living Plug._tplink._tcp.local.',
    host: 'living-plug.local',
    port: 80,
    txt: {
      model: 'KP125M',
      mac: 'F0-A7-31-00-11-22',
      alias: 'Living Plug',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('tplink');
  expect(result.normalizedDeviceId).toEqual('f0:a7:31:00:11:22');
});

tap.test('matches Home Assistant TP-Link DHCP rules', async () => {
  const descriptor = createTplinkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    hostname: 'HS110-Office',
    ipAddress: '192.168.1.44',
    macAddress: '50:C7:BF:AA:BB:CC',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.44');
});

tap.test('validates manual snapshot candidates', async () => {
  const descriptor = createTplinkDiscoveryDescriptor();
  const manualMatcher = descriptor.getMatchers()[2];
  const validator = descriptor.getValidators()[0];
  const manual = await manualMatcher.matches({
    host: '192.168.1.55',
    model: 'Tapo P110',
    alias: 'Desk Plug',
    snapshot: {
      connected: true,
      devices: [],
      entities: [],
      events: [],
    },
  }, {});
  const validated = await validator.validate(manual.candidate!, {});

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

export default tap.start();
