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

tap.test('matches Xiaomi Miio mDNS records', async () => {
  const descriptor = createXiaomiMiioDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'xiaomi-miio-mdns-match');
  const result = await matcher!.matches({
    type: '_miio._udp.local.',
    name: 'rockrobo-vacuum-v1_miio._udp.local.',
    host: '192.168.1.50',
    port: 54321,
    txt: { poch: 'mac=286c0789abcd', did: '123456789' },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('xiaomi_miio');
  expect(result.candidate?.model).toEqual('rockrobo.vacuum.v1');
  expect(result.candidate?.macAddress).toEqual('28:6c:07:89:ab:cd');
});

tap.test('matches manual host token entries and validates candidates', async () => {
  const descriptor = createXiaomiMiioDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'xiaomi-miio-manual-match');
  const validator = descriptor.getValidators()[0];
  const result = await matcher!.matches({
    host: '192.168.1.51',
    token: '00112233445566778899aabbccddeeff',
    model: 'zhimi.airpurifier.v2',
    name: 'Bedroom purifier',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.metadata?.tokenConfigured).toBeTrue();
  const validation = await validator.validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();
  expect(validation.confidence).toEqual('certain');
});

tap.test('matches Xiaomi Miio DHCP records', async () => {
  const descriptor = createXiaomiMiioDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'xiaomi-miio-dhcp-match');
  const result = await matcher!.matches({
    ipAddress: '192.168.1.52',
    hostname: 'roborock-vacuum',
    manufacturer: 'Xiaomi',
    macAddress: '28:6C:07:89:AB:CE',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.52');
  expect(result.candidate?.macAddress).toEqual('28:6c:07:89:ab:ce');
});

export default tap.start();
