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

tap.test('matches Plex GDM server responses', async () => {
  const descriptor = createPlexDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    data: {
      'Content-Type': 'plex/media-server',
      Name: 'Media Box',
      Port: '32400',
      'Resource-Identifier': 'server-abc',
      Version: '1.41.0',
    },
    from: ['192.168.1.10', 32414],
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('plex');
  expect(result.candidate?.host).toEqual('192.168.1.10');
  expect(result.candidate?.port).toEqual(32400);
  expect(result.normalizedDeviceId).toEqual('server-abc');
});

tap.test('matches Plex zeroconf records', async () => {
  const descriptor = createPlexDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    type: '_plexmediasvr._tcp.local.',
    name: 'Media Box._plexmediasvr._tcp.local.',
    host: 'media-box.local',
    port: 32400,
    txt: {
      machineIdentifier: 'server-abc',
    },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('media-box.local');
  expect(result.candidate?.metadata?.discoveryProtocol).toEqual('mdns');
});

tap.test('matches Plex SSDP records when advertised', async () => {
  const descriptor = createPlexDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[2];
  const result = await matcher.matches({
    headers: {
      location: 'http://192.168.1.10:32400/description.xml',
      server: 'Plex UPnP/1.0',
      usn: 'uuid:server-abc::urn:schemas-upnp-org:device:MediaServer:1',
    },
    friendlyName: 'Media Box Plex',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.10');
  expect(result.candidate?.port).toEqual(32400);
});

tap.test('matches and validates manual Plex entries', async () => {
  const descriptor = createPlexDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[3];
  const result = await matcher.matches({ host: '192.168.1.10', token: 'secret', name: 'Media Box' }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.port).toEqual(32400);

  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();
  expect(validation.confidence).toEqual('certain');
});

export default tap.start();
