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

tap.test('matches Matter zeroconf records', async () => {
  const descriptor = createMatterDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];

  const operational = await matcher.matches({
    type: '_matter._tcp.local.',
    name: 'Kitchen Bulb._matter._tcp.local.',
    host: 'kitchen-bulb.local',
    port: 5540,
    txt: { dn: 'Kitchen Bulb' },
  }, {});
  const commissionable = await matcher.matches({
    type: '_matterc._udp.local.',
    name: 'Commissionable._matterc._udp.local.',
    host: 'commissionable.local',
    port: 5540,
  }, {});

  expect(operational.matched).toBeTrue();
  expect(operational.candidate?.name).toEqual('Kitchen Bulb');
  expect(commissionable.matched).toBeTrue();
  expect(commissionable.candidate?.model).toEqual('Commissionable Matter device');
});

tap.test('manual Matter setup defaults to local server URL', async () => {
  const descriptor = createMatterDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({}, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.metadata?.url).toEqual('ws://localhost:5580/ws');
});

tap.test('Matter config flow uses candidate URL default', async () => {
  const flow = new MatterConfigFlow();
  const step = await flow.start({
    source: 'manual',
    metadata: { url: 'ws://matter.local:5580/ws' },
  }, {});
  const done = await step.submit?.({});

  expect(done?.config?.url).toEqual('ws://matter.local:5580/ws');
});

export default tap.start();
