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

tap.test('matches DLNA DMS SSDP records with required services', async () => {
  const descriptor = createDlnaDmsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-upnp-org:device:MediaServer:1',
    usn: 'uuid:server-1::urn:schemas-upnp-org:device:MediaServer:1',
    location: 'http://192.168.1.60:8200/rootDesc.xml',
    upnp: {
      friendlyName: 'Media Server',
      manufacturer: 'Example',
      modelName: 'DMS',
      serviceList: {
        service: [
          { serviceId: 'urn:upnp-org:serviceId:ContentDirectory' },
          { serviceId: 'urn:upnp-org:serviceId:ConnectionManager' },
        ],
      },
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('uuid:server-1::urn:schemas-upnp-org:device:MediaServer:1');
  expect(result.candidate?.integrationDomain).toEqual('dlna_dms');
  expect(result.candidate?.host).toEqual('192.168.1.60');
  expect(result.candidate?.metadata?.udn).toEqual('uuid:server-1');
});

tap.test('rejects DLNA DMS SSDP records missing required services', async () => {
  const descriptor = createDlnaDmsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-upnp-org:device:MediaServer:1',
    usn: 'uuid:server-1::urn:schemas-upnp-org:device:MediaServer:1',
    location: 'http://192.168.1.60:8200/rootDesc.xml',
    upnp: {
      serviceList: { service: [{ serviceId: 'urn:upnp-org:serviceId:ContentDirectory' }] },
    },
  }, {});

  expect(result.matched).toBeFalse();
  expect(result.reason).toContain('required DMS services');
});

tap.test('matches manual DLNA DMS entries and creates config', async () => {
  const descriptor = createDlnaDmsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({ url: 'http://media.local:8200/rootDesc.xml', name: 'Manual Media Server' }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.metadata?.location).toEqual('http://media.local:8200/rootDesc.xml');

  const flow = new DlnaDmsConfigFlow();
  const step = await flow.start(result.candidate!, {});
  expect(step.kind).toEqual('done');
  expect(step.config?.location).toEqual('http://media.local:8200/rootDesc.xml');
  expect(step.config?.sourceId).toEqual('manual_media_server');
});

export default tap.start();
