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

tap.test('matches Harmony Hub SSDP advertisements from the upstream manifest', async () => {
  const descriptor = createHarmonyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    deviceType: 'urn:myharmony-com:device:harmony:1',
    manufacturer: 'Logitech',
    friendlyName: 'Living Room Harmony',
    location: 'http://192.168.1.40:5224/description.xml',
    usn: 'uuid:harmony-hub-123::urn:myharmony-com:device:harmony:1',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('certain');
  expect(result.candidate?.integrationDomain).toEqual('harmony');
  expect(result.candidate?.host).toEqual('192.168.1.40');
  expect(result.candidate?.port).toEqual(8088);
  expect(result.candidate?.manufacturer).toEqual('Logitech');
  expect(result.candidate?.metadata?.ssdpDeviceType).toEqual('urn:myharmony-com:device:harmony:1');
});

tap.test('matches manual Harmony Hub host entries', async () => {
  const descriptor = createHarmonyDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    host: '192.168.1.41',
    name: 'Bedroom Hub',
    remoteId: '987654321',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.41');
  expect(result.candidate?.port).toEqual(8088);
  expect(result.normalizedDeviceId).toEqual('987654321');
});

tap.test('creates local-first config flow entries', async () => {
  const flow = new HarmonyConfigFlow();
  const step = await flow.start({ source: 'ssdp', host: '192.168.1.42', name: 'Office Hub', metadata: { remoteId: 'hub-42' } }, {});
  const done = await step.submit?.({ host: '192.168.1.42', defaultActivity: 'Watch TV' });

  expect(done?.kind).toEqual('done');
  expect(done?.config?.host).toEqual('192.168.1.42');
  expect(done?.config?.port).toEqual(8088);
  expect(done?.config?.remoteId).toEqual('hub-42');
  expect(done?.config?.defaultActivity).toEqual('Watch TV');
  expect(done?.config?.delaySecs).toEqual(0.4);
});

export default tap.start();
