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

tap.test('matches Home Assistant HEOS SSDP records', async () => {
  const descriptor = createHeosDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-denon-com:device:ACT-Denon:1',
    usn: 'uuid:heos-123::urn:schemas-denon-com:device:ACT-Denon:1',
    location: 'http://192.168.1.80:60006/upnp/desc/aios_device/aios_device.xml',
    upnp: {
      manufacturer: 'Denon',
      modelName: 'HEOS 7',
      serialNumber: 'HEOS12345',
      friendlyName: 'Living Room HEOS',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('certain');
  expect(result.normalizedDeviceId).toEqual('HEOS12345');
  expect(result.candidate?.host).toEqual('192.168.1.80');
  expect(result.candidate?.port).toEqual(1255);
});

tap.test('matches HEOS zeroconf and manual candidates', async () => {
  const descriptor = createHeosDiscoveryDescriptor();
  const mdns = await descriptor.getMatchers()[1].matches({
    name: 'Kitchen HEOS',
    type: '_heos-audio._tcp.local.',
    host: 'kitchen-heos.local',
    port: 10101,
    txt: { model: 'HEOS 5', serial: 'HEOS5678' },
  }, {});
  expect(mdns.matched).toBeTrue();
  expect(mdns.candidate?.port).toEqual(1255);

  const manual = await descriptor.getMatchers()[2].matches({ host: '192.168.1.81', name: 'Manual HEOS' }, {});
  expect(manual.matched).toBeTrue();
  expect(manual.candidate?.host).toEqual('192.168.1.81');

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

tap.test('rejects unrelated SSDP records', async () => {
  const descriptor = createHeosDiscoveryDescriptor();
  const result = await descriptor.getMatchers()[0].matches({
    st: 'urn:schemas-upnp-org:device:Printer:1',
    location: 'http://192.168.1.90/device.xml',
    upnp: { manufacturer: 'Brother', modelName: 'Printer' },
  }, {});
  expect(result.matched).toBeFalse();
});

export default tap.start();
