import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Go2rtcConfigFlow, createGo2rtcDiscoveryDescriptor } from '../../ts/integrations/go2rtc/index.js';

tap.test('matches manual go2rtc HTTP entries and configures flow', async () => {
  const descriptor = createGo2rtcDiscoveryDescriptor();
  const manualMatcher = descriptor.getMatchers()[0];
  const match = await manualMatcher.matches({ url: 'http://192.168.1.20:1984', name: 'go2rtc NVR' }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.integrationDomain).toEqual('go2rtc');
  expect(match.candidate?.host).toEqual('192.168.1.20');
  expect(match.candidate?.port).toEqual(1984);

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

  const flow = new Go2rtcConfigFlow();
  const step = await flow.start(match.candidate!, {});
  const done = await step.submit!({ protocol: 'http', host: '192.168.1.20', port: 1984, username: 'ha', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.url).toEqual('http://192.168.1.20:1984');
  expect(done.config?.username).toEqual('ha');
  expect(done.config?.rtsp?.port).toEqual(8554);
  expect(done.config?.webrtc?.port).toEqual(8555);
});

tap.test('matches HTTP candidates on the default go2rtc API port', async () => {
  const descriptor = createGo2rtcDiscoveryDescriptor();
  const httpMatcher = descriptor.getMatchers()[1];
  const match = await httpMatcher.matches({ url: 'http://go2rtc.local:1984', metadata: { version: '1.9.14' } }, {});

  expect(match.matched).toBeTrue();
  expect(match.confidence).toEqual('high');
  expect(match.candidate?.source).toEqual('http');
  expect(match.candidate?.metadata?.url).toEqual('http://go2rtc.local:1984');
});

export default tap.start();
