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

tap.test('matches LinkPlay zeroconf records', async () => {
  const descriptor = createLinkplayDiscoveryDescriptor();
  const result = await descriptor.getMatchers()[0].matches({
    name: 'Living Room._linkplay._tcp.local.',
    type: '_linkplay._tcp.local.',
    host: 'living-room.local',
    port: 80,
    txt: {
      uuid: 'leader-uuid',
      DeviceName: 'Living Room',
      project: 'ARYLIC_S50',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('certain');
  expect(result.normalizedDeviceId).toEqual('leader-uuid');
  expect(result.candidate?.manufacturer).toEqual('Arylic');
  expect(result.candidate?.model).toEqual('S50+');
});

tap.test('matches LinkPlay SSDP records only with LinkPlay hints', async () => {
  const descriptor = createLinkplayDiscoveryDescriptor();
  const result = await descriptor.getMatchers()[1].matches({
    st: 'urn:schemas-upnp-org:device:MediaRenderer:1',
    usn: 'uuid:linkplay-123::urn:schemas-upnp-org:device:MediaRenderer:1',
    location: 'http://192.168.1.10:49152/description.xml',
    upnp: {
      manufacturer: 'LinkPlay',
      modelName: 'Up2Stream Mini',
      friendlyName: 'Kitchen Speaker',
      serialNumber: 'LP123',
    },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.10');
  expect(result.candidate?.port).toEqual(80);

  const genericRenderer = await descriptor.getMatchers()[1].matches({
    st: 'urn:schemas-upnp-org:device:MediaRenderer:1',
    location: 'http://192.168.1.20/device.xml',
    upnp: { manufacturer: 'Generic Audio', modelName: 'Renderer' },
  }, {});
  expect(genericRenderer.matched).toBeFalse();
});

tap.test('matches and validates manual LinkPlay candidates', async () => {
  const descriptor = createLinkplayDiscoveryDescriptor();
  const manual = await descriptor.getMatchers()[2].matches({ host: '192.168.1.30', name: 'Manual LinkPlay', project: 'UP2STREAM_MINI_V3' }, {});
  expect(manual.matched).toBeTrue();
  expect(manual.candidate?.host).toEqual('192.168.1.30');
  expect(manual.candidate?.metadata?.protocol).toEqual('http');

  const validation = await descriptor.getValidators()[0].validate(manual.candidate!, {});
  expect(validation.matched).toBeTrue();
  expect(validation.normalizedDeviceId).toEqual('192.168.1.30:80');
});

export default tap.start();
