import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AgentDvrConfigFlow, createAgentDvrDiscoveryDescriptor } from '../../ts/integrations/agent_dvr/index.js';

tap.test('matches manual Agent DVR host entries and builds config flow output', async () => {
  const descriptor = createAgentDvrDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'agent-dvr-manual-match');
  const match = await matcher?.matches({ host: '192.168.1.90', name: 'Garage Agent DVR' }, {});

  expect(match?.matched).toBeTrue();
  expect(match?.candidate?.integrationDomain).toEqual('agent_dvr');
  expect(match?.candidate?.host).toEqual('192.168.1.90');
  expect(match?.candidate?.port).toEqual(8090);
  expect(match?.candidate?.metadata?.serverUrl).toEqual('http://192.168.1.90:8090/');

  const validation = await descriptor.getValidators()[0].validate(match!.candidate!, {});
  expect(validation.matched).toBeTrue();

  const flow = new AgentDvrConfigFlow();
  const step = await flow.start(match!.candidate!, {});
  const done = await step.submit!({ name: 'Garage DVR' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.168.1.90');
  expect(done.config?.port).toEqual(8090);
  expect(done.config?.serverUrl).toEqual('http://192.168.1.90:8090/');
  expect(done.config?.name).toEqual('Garage DVR');
});

tap.test('matches Agent DVR mDNS metadata without inventing a live probe', async () => {
  const descriptor = createAgentDvrDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'agent-dvr-mdns-match');
  const match = await matcher?.matches({
    name: 'Agent DVR._http._tcp.local',
    host: 'agent-dvr.local',
    port: 8090,
    txt: {
      manufacturer: 'iSpyConnect',
      model: 'Agent DVR',
      unique: 'agent-123',
    },
  }, {});

  expect(match?.matched).toBeTrue();
  expect(match?.candidate?.integrationDomain).toEqual('agent_dvr');
  expect(match?.candidate?.host).toEqual('agent-dvr.local');
  expect(match?.candidate?.metadata?.discoveryProtocol).toEqual('mdns');
  expect(descriptor.getProbes().length).toEqual(0);
});

export default tap.start();
