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

tap.test('matches manual Emby server URLs', async () => {
  const descriptor = createEmbyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'emby-manual-match');
  const result = await matcher?.matches({
    url: 'http://emby.local:8096',
    apiKey: 'local-token',
    name: 'Home Emby',
  }, {});
  expect(result?.matched).toBeTrue();
  expect(result?.candidate?.host).toEqual('emby.local');
  expect(result?.candidate?.port).toEqual(8096);
  expect(result?.candidate?.metadata?.apiKey).toEqual('local-token');
});

tap.test('matches Emby SSDP records', async () => {
  const descriptor = createEmbyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'emby-ssdp-match');
  const result = await matcher?.matches({
    st: 'urn:schemas-upnp-org:device:MediaServer:1',
    usn: 'uuid:emby-server-1::urn:schemas-upnp-org:device:MediaServer:1',
    location: 'http://192.168.1.30:8096/dlna/server/description.xml',
    server: 'Emby/4.8.0 UPnP/1.0',
    headers: {
      manufacturer: 'Emby',
      modelName: 'Emby Server',
    },
  }, {});
  expect(result?.matched).toBeTrue();
  expect(result?.normalizedDeviceId).toEqual('emby-server-1');
  expect(result?.candidate?.host).toEqual('192.168.1.30');
});

tap.test('validates and configures Emby candidates', async () => {
  const descriptor = createEmbyDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate({
    source: 'manual',
    integrationDomain: 'emby',
    host: '192.168.1.30',
    port: 8096,
  }, {});
  expect(validation.matched).toBeTrue();
  expect(validation.confidence).toEqual('high');

  const flow = new EmbyConfigFlow();
  const step = await flow.start(validation.candidate!, {});
  const done = await step.submit!({ url: 'https://emby.example.local:8920', apiKey: 'token-1', name: 'Main Emby' });
  expect(done.config?.host).toEqual('emby.example.local');
  expect(done.config?.port).toEqual(8920);
  expect(done.config?.ssl).toBeTrue();
  expect(done.config?.apiKey).toEqual('token-1');
});

export default tap.start();
