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

tap.test('matches Nanoleaf mDNS zeroconf records', async () => {
  const descriptor = createNanoleafDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'nanoleaf-mdns-match');
  const result = await matcher!.matches({
    name: 'Nanoleaf Shapes ABCD',
    type: '_nanoleafapi._tcp.local.',
    host: 'nanoleaf-shapes.local',
    port: 16021,
    txt: {
      id: 'NL123ABC',
      md: 'NL42',
    },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('NL123ABC');
  expect(result.candidate?.port).toEqual(16021);
});

tap.test('matches Nanoleaf SSDP records', async () => {
  const descriptor = createNanoleafDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'nanoleaf-ssdp-match');
  const result = await matcher!.matches({
    st: 'nanoleaf:nl42',
    usn: 'uuid:nanoleaf-nl42',
    headers: {
      '_host': '192.168.1.55:16021',
      'nl-devicename': 'Nanoleaf Shapes ABCD',
      'nl-deviceid': 'NL123ABC',
    },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.55');
  expect(result.candidate?.model).toEqual('NL42');
});

tap.test('validates manual Nanoleaf candidates', async () => {
  const descriptor = createNanoleafDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'nanoleaf-manual-match');
  const manualResult = await matcher!.matches({
    host: '192.168.1.56',
    port: 16021,
    metadata: { nanoleaf: true },
  }, {});
  expect(manualResult.matched).toBeTrue();

  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate(manualResult.candidate!, {});
  expect(validation.matched).toBeTrue();
});

export default tap.start();
