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

tap.test('matches DirecTV SSDP MediaServer records', async () => {
  const descriptor = createDirectvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-upnp-org:device:MediaServer:1',
    usn: 'uuid:RID-001122::urn:schemas-upnp-org:device:MediaServer:1',
    location: 'http://192.168.1.55:8080/device.xml',
    upnp: {
      friendlyName: 'Living Room DirecTV',
      manufacturer: 'DIRECTV',
      modelName: 'HR54',
      serialNumber: 'RID-001122',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('001122');
  expect(result.candidate?.host).toEqual('192.168.1.55');
  expect(result.candidate?.port).toEqual(8080);
  expect(result.candidate?.metadata?.receiverId).toEqual('001122');
});

tap.test('rejects non-DirecTV MediaServer SSDP records', async () => {
  const descriptor = createDirectvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-upnp-org:device:MediaServer:1',
    location: 'http://192.168.1.60/rootDesc.xml',
    upnp: { manufacturer: 'Example DLNA', friendlyName: 'Media Server' },
  }, {});

  expect(result.matched).toBeFalse();
  expect(result.reason).toContain('not a DirecTV');
});

tap.test('matches manual DirecTV entries and creates config', async () => {
  const descriptor = createDirectvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({ host: 'directv.local', receiverId: 'RID-ABC123', name: 'Manual DirecTV' }, {});
  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('ABC123');

  const flow = new DirectvConfigFlow();
  const step = await flow.start(result.candidate!, {});
  expect(step.kind).toEqual('done');
  expect(step.config?.host).toEqual('directv.local');
  expect(step.config?.port).toEqual(8080);
  expect(step.config?.receiverId).toEqual('ABC123');
});

export default tap.start();
